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

穆罕默德·法拉格(Mohamed Farrag)

我的代码很简单,例如:

[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

我不认为对每个引用进行空检查的最佳实践是:

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

你能告诉我为什么有时它为空吗?有时不是吗?最佳做法是什么?

琼·卡隆

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

Page.User.Identity.IsAuthenticated返回未设置为对象实例的对象引用

在内部,Request.IsAuthenticated将验证是否已设置用户及其身份(不为null)。您可以在代码中做同样的事情,但是为什么要麻烦呢。

调用以下方法时,将设置User.Identity.IsAuthenticated:

FormsAuthentication.Authenticate(name, pwd)

或者

Membership.ValidateUser(name, pwd)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档