【发布时间】: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