I have a Web API with a Base Controller, I wanna get requested controller name from Request.GetRouteData().Values["controller"]
, as the following code :
public class BaseApiController : ApiController
{
protected string EntityName;
public BaseApiController()
{
//Request is null
EntityName = Request.GetRouteData().Values["controller"] as string;
}
}
But Request is always null in above code.
What's wrong with above code?
You just cannot use the Request
property in the Controller
's c'tor. It gets called before the actual request is handed over to it by the framework.
If you need Headers, you can use HttpContext.Current.Request.Headers
This is expected - you're in the controllers constructor. The controller hasn't been initialized with the actual request yet. Try something like the following:
protected string EntityName
{
get { Request.GetRouteData().Values["controller"] as string; }
}
That should be accessible after the constructor has run, and when you're in a subclass method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With