首页 > 解决方案 > 发送会话以在 Asp.Net MVC 上查看时出现问题

问题描述

我想阻止客户端在未登录时访问路由 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). 我意识到编译器<h2>Hello @Session["userName"].ToString() </h2>在检查 if 语句然后返回 if 之前先去。

标签: asp.net-mvcrazorsession-cookiesnullreferenceexception

解决方案


只需删除.ToString(). 没有它,它应该正确呈现字符串。


推荐阅读