Cookie中的ASP.net MVC文化信息



我刚刚遇到一个相当奇怪的问题,我真的不明白为什么会发生这种情况。。。

我有一个相当简单的基于.NET Framework 4.7.2的MVC网站。我为几种语言保留了2个资源文件(resx(。到目前为止还不错。我所做的是用CultureInfo(en-US&el-GR(将选定的文化保存在Cookie中。在我的开发机器中,使用IISExpress,一切都像魅力一样运行!cookie正在按预期进行更新,当然,从浏览器调试中可以看到值的切换。

使用Global.asax中的Application_BeginRequest((,我可以恢复所选区域性:

protected void Application_BeginRequest(object sender, EventArgs e)
{
string culture = "el-GR";
var langCookie = Request.Cookies["SiderLangCookie"];
if (langCookie != null)
culture = langCookie.Value;
else
{
culture = "el-GR";
HttpCookie cookie = new HttpCookie("SiderLangCookie", culture)
{
HttpOnly = true,
Expires = DateTime.Now.AddMonths(6)
};
Response.AddHeader("Set-Cookie", "SameSite=Strict;Secure");
Response.AppendCookie(cookie);
}
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
}

稍后,如果用户选择这样做,他/她可能会从锚点按钮更改区域性:

<a class="socials-item" href="javascript:SwitchLanguage();" title="Language"><i class="fa fa-flag" aria-hidden="true"></i></a>

它正在为控制器动作调用AJAX POST请求的javascript函数:

function SwitchLanguage() {
$.ajax({
url: '@Url.Action("SwitchLanguage", "Home")',
method: 'POST',
success: function (response) {
if (response.result == "OK") {
toastr.success("@Resource.LanguageSwitchSuccess", "SUCCESS");
setTimeout(function () { window.location.reload(); }, 2500);
}
},
error: function () {
toastr.error("@Resource.LanguageSwitchError", "ERROR");
}
});
}

这是我的行动:

[HttpPost]
public ActionResult SwitchLanguage()
{
string lang = "en-US";
var langCookie = Request.Cookies["SiderLangCookie"];
if (langCookie == null)
{
langCookie = new HttpCookie("SiderLangCookie", lang)
{
HttpOnly = true,
Expires = DateTime.Now.AddMonths(6),
};
Response.AddHeader("Set-Cookie", "SameSite=Strict;Secure");
Response.AppendCookie(langCookie);
}
else
{
lang = langCookie.Value;
if (lang == "en-US")
lang = "el-GR";
else
lang = "en-US";
langCookie.Value = lang;
Response.AddHeader("Set-Cookie", "SameSite=Strict;Secure");
Response.SetCookie(langCookie);
}
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
return Json(new { result = "OK" }, JsonRequestBehavior.AllowGet);
}

出于某种原因,当我部署网站(发布到文件夹并上传到主机(时,即使操作代码执行成功(没有任何异常和错误(,cookie也不再将值更新为el-GR或en-US。它只是坚持最初创建时获得的第一个值。

有人知道为什么会发生这种事吗?

提前谢谢。

如果您在web.config上没有正确设置相关会话,则通常会出现Cookie问题。

在没有www.的情况下检查正确设置的domain-如果使用www.,则检查所有从www.完成的调用

<httpCookies domain="yourdomain.com" httpOnlyCookies="true" requireSSL="true"/> 

domain性质也存在于formsroleManager

好的,我设法弄清楚了情况。非常感谢Thomas Ardal,他写了这篇文章:

[在.NET中使用web.config保护cookie的终极指南][1][1] :https://blog.elmah.io/the-ultimate-guide-to-secure-cookies-with-web-config-in-net/

浏览器对Cookie管理的最新变化似乎比预期的更具限制性。

托马斯建议,将重写规则纳入其中,起到了一定的作用。

现在Cookie值似乎正在按预期进行更改。

感谢

最新更新