Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request is always null in web api?

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?

like image 490
Mohammad Dayyan Avatar asked Dec 06 '13 16:12

Mohammad Dayyan


3 Answers

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.

like image 26
Thomas Weller Avatar answered Oct 03 '22 05:10

Thomas Weller


If you need Headers, you can use HttpContext.Current.Request.Headers

like image 41
Elan Hasson Avatar answered Oct 03 '22 05:10

Elan Hasson


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.

like image 124
matt Avatar answered Oct 03 '22 06:10

matt