【问题标题】:Why can't I access the HttpContext from the Controller initializer?为什么我不能从 Controller 初始化程序访问 HttpContext?
【发布时间】:2011-07-28 03:28:30
【问题描述】:

我有一个这样设置的控制器:

public class GenesisController : Controller
{

    private string master;
    public string Master { get { return master; } }

    public GenesisController()
    {
        bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
        if (mobile)
            master="mobile";
        else
            master="site";
    }

}

我所有的其他控制器都继承自这个 GenesisController。每当我运行应用程序时,我都会收到此错误提示

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

如何访问 HttpContext 并从控制器初始化?

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    因为 HttpContext 在控制器构造函数中不可用。您可以覆盖可访问的 Initialize 方法,如下所示:

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
        if (mobile)
            master="mobile";
        else
            master="site";
    }
    

    我还敢打赌,您尝试用这个主变量和布尔值做的事情可能会在 far more elegant way 中解决,而不是让您的控制器担心这样的事情。

    【讨论】:

    • 感谢您提供指向 Scott Hanselman 文章的链接。起初我认为他的方法过于复杂而且有点矫枉过正......但在使用我的方法后,我意识到需要考虑所有不同的场景。现在,我已经按照自己的方式工作了。但是,当我重新访问实时站点时,我可能会关注 Scott 的文章。
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多