asp.net-mvc - 发送会话以在 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 之前先去。
解决方案
只需删除.ToString()
. 没有它,它应该正确呈现字符串。
推荐阅读
- php - 为什么我的 Highcharts 堆积面积样条图看起来很有趣?
- c++ - if constexpr vs if with constant
- jms - ActiveMQ:我们可以使用单个消息发送多个文件吗
- javascript - 如何在 javascript 的事件处理函数中正确使用变量
- sql - SQL 只返回带有数据的行,而不是那些为 0 的行
- javascript - 在输入过程中使文本实时显示在画布上
- grails-3.3 - 服务器启动期间出现 UnsatisfiedDependencyException
- xhtml - 如何修复 xhtml 代码中的“无法进行模数转换”错误
- python-3.x - 如何处理代理在带有 x 和 y 坐标的嵌套列表中移动
- javascript - 使用 HTML5 输入的离子文件上传