【发布时间】:2021-06-10 01:02:23
【问题描述】:
我刚刚遇到了一个相当奇怪的问题,我真的不明白为什么会这样......
我有一个基于 .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。它只是坚持第一次创建时获得的第一个值。
有人知道为什么会这样吗?
提前致谢。
【问题讨论】:
标签: asp.net-mvc iis cookies cultureinfo