简体   繁体   中英

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?

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.

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.

如果需要Headers,可以使用HttpContext.Current.Request.Headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM