Alex Rivera | Logout

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

Asked 2008-10-21T20:12:56.237
30

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?

Edit
Report

1 Answer

26

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.

answered 2008-10-22T14:19:29.227

Your Answer