【发布时间】:2020-01-14 05:56:09
【问题描述】:
我想阻止客户端在未登录时访问路由 Home/Index。所以我认为的代码在这里:
@{
Layout = null;
if (Session["userId"]==null)
{
Response.Redirect(Url.Action("Index","Login"));
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>QIndex</title>
</head>
<body>
<div>
<h1>Profile</h1>
<h2>Hello @Session["userName"].ToString() </h2>
<a href=@Url.Action("LogOut","Login")>خروج</a>
</div>
</body>
</html>
问题是当我消除@Session["userName"].ToString() 时,一切正常。但是当这没有消除时,System.NullReferenceException: 'Object reference not set to an instance of an object.' 这一行就会出现错误。
我在if (Session["userId"]==null) 上设置了一个断点。我意识到编译器在检查 if 语句然后返回 if 之前会转到 <h2>Hello @Session["userName"].ToString() </h2>。
【问题讨论】:
标签: asp.net-mvc razor session-cookies nullreferenceexception