如何在mvc5中将文化设置为全局
本文关键字:文化 设置 全局 mvc5 | 更新日期: 2023-09-27 18:06:57
我使用资源文件在我的web应用程序中切换语言,这是在mvc5中构建的
在索引文件中读取我设置的区域性值。
我正在从布局中调用设置文化方法。CSHTML并使用以下代码调用其值:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
if (!Request["dropdown"].IsEmpty())
{
Culture = UICulture = Request["dropdown"];
}
}
在索引页的语言是正确加载的,但当从那里,当我去到下一页加载默认语言德语,但从英语资源文件中读取资源。
对于全局设置,我建议您在global.asax.cs文件中添加以下行:(在本例中,文化设置为以色列希伯来语)
protected void Application_Start()
{
//The culture value determines the results of culture-dependent functions, such as the date, number, and currency (NIS symbol)
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("he-il");
//System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("he-il");
}
在web.config
中,我在里面注释了下面一行,它对我来说工作得很好。
<configuration>
<system.web>
<globalization culture="en-US" uiCulture="en-US" /> <!-- this only -->
</system.web>
</configuration>
你必须在某个地方保存当前文化的信息(我建议cookie),并将线程文化设置为这个cookie值(如果存在)-最好在Global.asax
的Application_BeginRequest
中。
public ActionResult ChangeCulture(string value) {
Response.Cookies.Add(new HttpCookie("culture", value));
return View();
}
public class MvcApplication : HttpApplication {
protected void Application_BeginRequest() {
var cookie = Context.Request.Cookies["culture"];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value)) {
var culture = new CultureInfo(cookie.Value);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}