Is the request always null in the web api?

I have a web API with a base controller, I want to get the requested controller name from Request.GetRouteData().Values["controller"], like the following code:

public class BaseApiController : ApiController
{
    protected string EntityName;

    public BaseApiController()
    {
        //Request is null
        EntityName = Request.GetRouteData().Values["controller"] as string;
    }
}

But the request is always zero in the code.
What is wrong with the above code?

+4
source share
3 answers

You are expected to be in the controller designer. The controller has not yet been initialized with the actual request. Try the following:

protected string EntityName 
{
  get { Request.GetRouteData().Values["controller"] as string; }
}

This should be available after starting the constructor and when you are in the subclass method.

+5
source

Request Controller c'tor. , .

+6

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

+1
source

All Articles