Getting HttpRequest context in self-hosted WebApi

2020-03-23 18:23发布

问题:

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.

回答1:

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?



回答2:

HttpContext.Current isn't available in self hosted projects

see: HttpSelfHostServer and HttpContext.Current