C# 在自托管 WebApi 中获取 HttpRequest 上下文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14349557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting HttpRequest context in self-hosted WebApi
提问by Alwyn
How can I access the query string from a self hosted MVC WebAPI?
如何从自托管的 MVC WebAPI 访问查询字符串?
Call to the following failed with NRE, because Current is empty (aka. null)
使用 NRE 调用以下失败,因为 Current 为空(又名 null)
System.Web.HttpContext.Current.Request["myQuery"]
I need access to the current context outside of the controller, since I want to control my object instantiation via. DI. eg.
我需要访问控制器外部的当前上下文,因为我想通过它来控制我的对象实例化。DI。例如。
container
.RegisterType<MyObject>(
new InjectionFactory(
uc =>
new MyObject(
System.Web.HttpContext.Current.Request["myParam"]) //This failed.
));
Call to container.Resolve<MyObject>()
from inside the ControllerApi code failed, because of the above NRE.
container.Resolve<MyObject>()
由于上述 NRE,从 ControllerApi 代码内部调用失败。
回答by Frazell Thomas
HttpContext.Current isn't available in self hosted projects
HttpContext.Current 在自托管项目中不可用
回答by Darrel Miller
You shouldn't really use System.Web.HttpContext.Current
in Web API. It is only valid when using Web Host and is really only there for legacy reasons. Context information is tucked away in the HttpRequestMessage.Properties
collection.
您不应该真正System.Web.HttpContext.Current
在 Web API 中使用。它仅在使用 Web Host 时有效,并且实际上只是出于遗留原因。上下文信息隐藏在HttpRequestMessage.Properties
集合中。
One of the ways that Web API improves testability is by removing its dependence on static properties.
Web API 提高可测试性的方法之一是消除其对静态属性的依赖。
There are ways to deal with resolving of instances and passing parameters. See this question Unity Application Block, How pass a parameter to Injection Factory?
有一些方法可以处理实例的解析和传递参数。看到这个问题Unity Application Block, How pass a parameter to Injection Factory?