请求在web api中始终为空?(Request is always null in web api?)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
请求在web api中始终为空?(Request is always null in web api?)

我有一个带有基本控制器的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.

更多推荐

本文发布于:2023-04-21 18:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a593eaf2d7818eed330a68dc287e6cf6.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   api   web   Request   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!