HttpContext.User.Identity.IsAuthenticated throws System.NullReferenceException:对象引用未设置为对象的实例

时间:2014-11-03 15:07:53

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

我的代码很简单:

[HttpGet]
public ActionResult Login ()
{
   if (User.Identity.IsAuthenticated)
   {
      return RedirectToAction("Index", "Home");
   }
   return View(new LoginModel());
}

[HttpPost]
public ActionReslt Login (LoginModel model)
{
    if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.Email, model.Password))
              {
                  FormsAuthentication.SetAuthCookie(model.Email, false);

                  return RedirectToAction("Index","Home");
              }
        }

    return View(model);
}

但我的日志服务有时会收到此错误! System.NullReferenceException: Object reference not set to an instance of an object

我认为对每个引用执行null检查的最佳做法如下:

if (User!=null && User.Identity!=null && User.Identity.IsAuthenticated)

你能告诉我为什么有时候它是空的吗?有时候不是吗? 它的最佳实践是什么?

1 个答案:

答案 0 :(得分:3)

您应该使用Request.IsAuthenticated而不是User.Identity.IsAuthenticated

Page.User.Identity.IsAuthenticated returns object reference not set to instance of object

  

内部Request.IsAuthenticated将验证用户及其   设置标识(非空)。您可以在代码中执行相同操作,但是   为什么这么麻烦。

调用这些方法时会设置User.Identity.IsAuthenticated:

FormsAuthentication.Authenticate(name, pwd)

或者

Membership.ValidateUser(name, pwd)

或其他设置Cookie的身份验证机制方法

相关问题