我有一个带有基本 Controller 的 Web API,我想从 Request.GetRouteData().Values["controller"]
获取请求的 Controller 名称,如下代码:
public class BaseApiController : ApiController
{
protected string EntityName;
public BaseApiController()
{
//Request is null
EntityName = Request.GetRouteData().Values["controller"] as string;
}
}
但是Request在上面的代码中总是null。
上面的代码有什么问题?
最佳答案
这是预料之中的——您在 Controller 构造函数中。 Controller 尚未用实际请求初始化。尝试如下操作:
protected string EntityName
{
get { Request.GetRouteData().Values["controller"] as string; }
}
在构造函数运行之后,以及当您在子类方法中时,应该可以访问它。
关于c# - Web api 中的请求始终为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428305/