1

我正在我的控制器类的构造函数中检查会话并出现Object reference not set to an instance of an object.错误

if (Session["MemberId"] == null)
{
  //....Redirect to login page
}

为什么这个错误是可能的?我还能做什么?这有什么必要的吗?就像在 php 中我们需要session_start()在检查会话值之前一样?

4

1 回答 1

5

Session is indeed null during the construction of your Controller. Try this instead:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    if (requestContext.HttpContext.Session["MemberId"] == null)
    {
        //....Redirect to login page
    }

    base.Initialize(requestContext);
}

See MSDN.

于 2013-10-14T14:50:58.327 回答