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?
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.