c# - 会话变量在 IE 中在重定向时丢失
问题描述
我有一个 MVC 应用程序,我正在使用会话变量来存储一个变量来识别登录用户。除了 IE,这在任何地方都可以正常工作。第一次登录将起作用,但如果我注销,删除会话变量,然后重新登录,它将不会再次设置会话变量。我正在做一个 Response.Redirect 注销后返回登录页面。
我尝试了多种方法,包括更改为 Server.Transfer 请求和设置伪造的 P3P 标头,因为显然 IE 仍然会读取它!该域没有下划线,这显然也是 IE 中的一个问题。对此的任何帮助将不胜感激!
Login:
Session.Add("UserID", extr_user.extr_id);
Logout:
Session.Remove("UserID");
Response.Redirect(Url.Action("Login", "Home"));
编辑
测试代码以模拟丢失会话变量的问题,该问题在服务器和本地主机上都明显运行
在此处下载代码
家庭控制器:
public class HomeController : Controller
{
public ActionResult Login()
{
return View();
}
public ActionResult Home()
{
if (Session["UserID"] == null)
{
Response.Redirect(Url.Action("Login"));
}
return View();
}
public string doLogin(string Email, string Password)
{
Session.Add("UserID", 1);
return Url.Action("Home");
}
public void Logout()
{
Session.Remove("UserID");
Response.Redirect(Url.Action("Login"));
}
}
主页.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
<a href="@Url.Action("Logout", "Home")">Logout</a>
</div>
</body>
</html>
登录.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
@model LoginTest.Models.User
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
function Login() {
var email = $("#Username").val();
var password = $("#Password").val();
$.ajax({
url: '@Url.Action("doLogin", "Home")',
type: 'GET',
data: { Email: email, Password: password },
dataType: "html",
success: function (data) {
window.location.replace(data);
},
Error: function (xhr, status, error) {
console.log(error);
}
});
}
</script>
</head>
<body>
<div>
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.TextBoxFor(m => m.Password)
</div>
<div>
<input type="button" id="btnLogin" onclick="Login()" value="Login" />
</div>
</body>
</html>
路由配置.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Home", id = UrlParameter.Optional }
);
}
}
解决方案
在这里发现问题,IE正在缓存ajax调用。解决的 2 个步骤,首先将 cache: false 添加到 ajax 参数。其次,您在 jquery 函数中拥有的任何 console.logs 都将其删除,因为 ie 仍然会缓存结果。
推荐阅读
- flutter - 在 Flutter 中使用橡皮擦覆盖图像
- javascript - 无法让 Greasemonkey 脚本专注于 VirusTotal.com 上的文本框
- python - Python - 更新多行
- c# - Visual Studio for Mac 不允许我创建新的表单项目
- reactjs - 我列出了我的关键道具,但仍然收到以下错误:列表中的每个孩子都应该有一个唯一的“关键”道具
- prestashop - WebServices 更新是否有任何默认触发器(挂钩)?
- javascript - 我尝试在 p5.js 中保存 27 张图片,但只有 10 张保存到我的下载文件夹中。为什么所有文件都没有保存?
- jboss - 如何在 JBoss 7.1.1 中使用 MySQL8.0.19?
- node.js - 我应该使用的最大查询参数 url 是多少?
- python - 同一个numpy数组中的不同十进制格式