[ACCEPTED]-HttpContext on instances of Controllers are null in ASP.net MVC-httpcontext

Accepted answer
Score: 64

For now I'm going to do the following. This 5 seems to be an acceptable fix...

public new HttpContextBase HttpContext {
    get {
        HttpContextWrapper context = 
            new HttpContextWrapper(System.Web.HttpContext.Current);
        return (HttpContextBase)context;                

Where this 4 is added to a Controller class these Controllers 3 are inheriting from.

I'm not sure if the 2 HttpContext being null is the desired behavior, but 1 this will fix it in the meantime for me.

Score: 24

Controllers are not designed to be created 4 manually like you're doing. It sounds like 3 what you really should be doing is putting 2 whatever reusable logic you have into a 1 helper class instead.

Score: 5

The HttpContext, in the ControllerContext 21 is null because it is not set when the controller 20 is created. The contructor of the controller 19 does not assign this property, so it will 18 be null. Normally, the HttpContext is set 17 to the HttpContext of the ControllerBuilder 16 class. Controllers are created by the ControllerBuilder 15 class, followed by the DefaultControllerFactory. When 14 you want to create your own instance of 13 a controller, you can use the ExecuteMethod 12 of the controller with your own ControllerContext. You 11 don't want to do that is a real application. When 10 you get some more experience with the framework 9 you will find the appropriate method to 8 do want you want. When you need ControllerContext 7 in Unit test, you can use a mocking framework 6 to mock the ControllerContext or you can 5 class faking it.

You can find a model of 4 the request flow in asp.net mvc on this blog.

When 3 your new to Asp.net mvc, it's worth the 2 effort to download the source code and read 1 an trace the route how a request is processed.

Score: 0

Is it that you want to use some functionality 6 from the controller? Or have the controller 5 perform an action?

If it's the former, maybe 4 that's some code that should be split out 3 into another class. If it's the latter, you 2 can do this to simply have that controller 1 do a specific action:

return RedirectToAction("SomeAction", "SomeOtherController", new {param1 = "Something" });

Score: 0

Are you using a controller factory? If 6 so, how are you registering components?

I 5 ran into this problem where I had inadvertently 4 added an HttpContext-based dependency as 3 a Singleton, rather than Transient in Windsor.

HttpContext 2 was null for all but the first request. It 1 took me a while to track down that one.

More Related questions