如何在MVC5中将文化设置为全局

9
我在使用资源文件来切换语言,我的网页应用是在mvc5中构建的。在索引文件中,它会读取我设置的区域值。我从layout.cshtml中调用了set culture方法,并用以下代码调用其值。
@{
Layout = "~/Views/Shared/_Layout.cshtml";

if (!Request["dropdown"].IsEmpty())
{
    Culture = UICulture = Request["dropdown"];
}

在首页时,语言加载正确,但是当我从那里进入下一页时,它加载默认语言德语,但资源仅从英语资源文件中读取。请帮我解决这个问题,谢谢任何人的帮助。
3个回答

22

全局设置建议您将以下行添加到 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");


    }

1
这正是我在寻找的。对于多线程Web应用程序,CurrentThread解决方案不起作用。它只会更改主线程的文化。 - DLL_Whisperer

16

web.config文件中,我注释掉了 <system.webServer>标签中的以下行,并且这对我来说运行良好。

<configuration>
   <system.web>
    <globalization culture="en-US" uiCulture="en-US" />  <!-- this only -->
   </system.web>
</configuration>

4

您需要将有关当前文化的信息存储在某个地方(我建议使用cookie),并将线程文化设置为此cookie值(如果存在) - 最好在Global.asaxApplication_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;
    }
  }
}

1
Uiculture和Thread culture的用途不同。请查看此链接:https://dev59.com/Omkw5IYBdhLWcg3w_fmK - user1409909
@Zekth - 我知道 :) 但Sajna Ali首先将它们设置为相同的值; 所以我想这就是他想要的。 - Ondrej Svejdar
1
将测试放在Application_BeginRequest()中有点重。每次请求时都会进行测试。 :/ - user1409909
1
@Zeth - 这是唯一的方法,因为每个请求都会启动一个新线程,您需要为每个请求设置正确的区域设置;) Sajna Ali - 请详细说明一下,这感觉像是不同的问题。 - Ondrej Svejdar
@Zekth 在资源文件的帮助下,我正在我的索引页面中切换语言。如Ondrej Svejdar所述,文化名称存储为上面的格式。我在第二个页面中放置了一个变量,如var culture = System.Globalization.CultureInfo.DefaultThreadCurrentUICulture; --- 它加载默认语言德语。在同一页中,我从资源中调用名称,但它显示为英语。 - TechNo
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接