简体   繁体   English

Web api中的请求始终为null?

[英]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 : 我有一个带有基本控制器的Web API,我想从Request.GetRouteData().Values["controller"]获取请求的控制器名称Request.GetRouteData().Values["controller"] ,如下代码:

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. 但在上面的代码中,Request始终为null。
What's wrong with above code? 上面的代码出了什么问题?

You just cannot use the Request property in the Controller 's c'tor. 你不能在Controller的c'tor中使用Request属性。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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