【问题标题】:HttpContext.User.Identity.IsAuthenticated throws System.NullReferenceException: Object reference not set to an instance of an objectHttpContext.User.Identity.IsAuthenticated 抛出 System.NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2022-04-28 14:26:56
【问题描述】:

我的代码很简单:

[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)

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

【问题讨论】:

  • NullReferenceException 是程序员的常见情况。提供的链接应该可以帮助您理解问题。然后使用调试器查找什么/在哪里/什么时候你有一个变量是null
  • 他清楚地知道 NullReferenceException 是什么以及如何修复它。这不是他的问题。
  • 是的,正如琼斯所说,我知道NullReferenceException,但我想知道为什么它有时会抛出异常,有时不会,我可以进行空检查,但我正在使用User.Identity.IsAuthenticated在很多地方,我不希望我的代码因为空检查而变得糟糕。而且它在调试模式下总是不为空,所以我从来没有收到这个错误。
  • @Figo,您能否展示一下您如何验证您的用户?问题可能就在那里。此外,使用Request.IsAuthenticated 而不是User.Identity.IsAuthenticated 可能更安全。

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


【解决方案1】:

您应该使用 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)

或其他设置cookies的Authentication机制方法

【讨论】:

  • 谢谢,我认为这是正确的方法,我还阅读了 Request.IsAuthenticated 和 User.Identity.IsAuthenticated 之间的区别
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多