对HttpContext的控制器的实例在ASP.net MVC为空 [英] HttpContext on instances of Controllers are null in ASP.net MVC
问题描述
这可能不是使用控制器的正确方法,但我也注意到这个问题,并没有想出一个办法来纠正它。
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
}
我注意到的HttpContext上的控制器是不是实际的HttpContext,你会发现在System.Web.HttpContext.Current。
I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current.
是否有某种方式来手动填充一个控制器的HttpContextBase?或者更好的方式来创建一个控制器的一个实例?
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.
这篇关于对HttpContext的控制器的实例在ASP.net MVC为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!