5

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Alwyn
  • 8,079
  • 12
  • 59
  • 107

2 Answers2

11

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?

Community
  • 1
  • 1
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
6

HttpContext.Current isn't available in self hosted projects

see: HttpSelfHostServer and HttpContext.Current

Community
  • 1
  • 1
Frazell Thomas
  • 6,031
  • 1
  • 20
  • 21
  • Frazell, thanks, but who's going to SetContext? I want this to be done automatically, and I hate to have to wire this up myself via filters/ webapi extension. – Alwyn Jan 16 '13 at 01:35