开发者

Why can't I access the HttpContext from the Controller initializer?

I have a controller set up like this:

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";
    }

}

All of my other controllers inherit from this GenesisController. Whenever I run the application, i get this error saying

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

How can I access HttpContext and开发者_StackOverflow中文版 from the controller initialization?


Because the HttpContext is not available in the controller constructor. You could override the Initialize method where it will be accessible, like this:

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";
}

Also I bet that what you are trying to do with this master variable and booleans might be solved in a far more elegant way than having your controllers worry about stuff like this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜