Getting HttpRequest context in self-hosted WebApi

2020-03-23 17:50发布

How can I access the query string from a self hosted MVC WebAPI?

Call to the following failed with NRE, because Current is empty (aka. 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.

        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.

2条回答
家丑人穷心不美
2楼-- · 2020-03-23 18:36

HttpContext.Current isn't available in self hosted projects

see: HttpSelfHostServer and HttpContext.Current

查看更多
我命由我不由天
3楼-- · 2020-03-23 18:40

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.

One of the ways that Web API improves testability is by removing its dependence on static properties.

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?

查看更多
登录 后发表回答