我有一个带有基本控制器的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; } }但是在上面的代码中Request始终为空。 上面的代码有什么问题?
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?
最满意答案
这是预期的 - 你在控制器构造函数中。 控制器尚未用实际请求初始化。 尝试如下所示:
protected string EntityName { get { Request.GetRouteData().Values["controller"] as string; } }这应该可以在构造函数运行后以及在子类方法中访问。
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.
更多推荐
发布评论