Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HttpRequest context in self-hosted WebApi

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.

like image 448
Alwyn Avatar asked Jan 16 '13 00:01

Alwyn


2 Answers

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?

like image 160
Darrel Miller Avatar answered Oct 17 '22 22:10

Darrel Miller


HttpContext.Current isn't available in self hosted projects

see: HttpSelfHostServer and HttpContext.Current

like image 6
Frazell Thomas Avatar answered Oct 17 '22 21:10

Frazell Thomas