在ASP.net MVC中,控制器实例上的HttpContext为null

Hug*_*are 28 asp.net-mvc httpcontext

这可能不是使用控制器的正确方法,但我确实注意到了这个问题并且没有找到解决方法.

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        

}
Run Code Online (Sandbox Code Playgroud)

我注意到Controller上的HttpContext不是你在System.Web.HttpContext.Current中找到的"实际"HttpContext.

有没有办法在Controller上手动填充HttpContextBase?或者更好的方法来创建Controller的实例?

Hug*_*are 62

现在我要做以下事情.这似乎是一个可接受的解决方案......

public new HttpContextBase HttpContext {
    get {
        HttpContextWrapper context = 
            new HttpContextWrapper(System.Web.HttpContext.Current);
        return (HttpContextBase)context;                
    }
}
Run Code Online (Sandbox Code Playgroud)

如果将其添加到Controller类,则这些控制器将继承自.

我不确定HttpContext是否为null是期望的行为,但是这将在此期间修复它.


Bra*_*son 24

控制器不是设计为像您一样手动创建的.听起来你真正应该做的就是将你拥有的任何可重用逻辑放入一个帮助类中.


Pac*_*aco 5

ControllerContext中的HttpContext为null,因为在创建控制器时未设置它.控制器的构造函数不分配此属性,因此它将为null.通常,HttpContext设置为ControllerBuilder类的HttpContext.控制器由ControllerBuilder类创建,后跟DefaultControllerFactory.如果要创建自己的控制器实例,可以将控制器的ExecuteMethod与自己的ControllerContext一起使用.你不想这样做是一个真正的应用程序.当您获得更多使用框架的经验时,您将找到适合您想要的方法.当您在单元测试中需要ControllerContext时,您可以使用模拟框架来模拟ControllerContext,或者您可以对其进行伪造.

您可以在此博客上找到asp.net mvc中的请求流模型.

当您刚接触Asp.net mvc时,值得努力下载源代码并读取跟踪请求的处理方式.