HttpContext on instances of Controllers are null in ASP.net MVC

38,554

Solution 1

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

Solution 2

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

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

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

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

Solution 3

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

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

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

Share:
38,554
user1709101
Author by

user1709101

Designer, developer, geek-dad

Updated on July 09, 2022

Comments

  • user1709101
    user1709101 almost 2 years

    This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it.

    public JsonResult SomeControllerAction() {
    
        //The current method has the HttpContext just fine
        bool currentIsNotNull = (this.HttpContext == null); //which is false    
    
        //creating a new instance of another controller
        SomeOtherController controller = new SomeOtherController();
        bool isNull = (controller.HttpContext == null); // which is true
    
        //The actual HttpContext is fine in both
        bool notNull = (System.Web.HttpContext.Current == null); // which is false        
    
    }
    

    I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current.

    Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?