本文介绍了如何在ASP .NET MVC中使用Resources和CultureInfo更改网站语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要支持的每种语言都有多个资源文件,如下所示:

I have several resource files for each language I want to support, named like below:

NavigationMenu.en-US.resx
NavigationMenu.ru-RU.resx
NavigationMenu.uk-UA.resx

文件位于 MySolution/Resources/NavigationMenu 文件夹中.

我有操作设置如下所示的 CurrentCulture CurrentUICulture

I have action which sets CurrentCulture and CurrentUICulture like below

public ActionResult SetLanguage(string lang)
{
    try
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        return Redirect(Request.UrlReferrer.AbsoluteUri);
    }
    catch(Exception)
    {
        return RedirectToAction("Index");
    }
}

lang 参数值是 uk-UA ru-RU en-US ,具体取决于链接在我看来被点击了.另外,我还定义了Web配置全球化部分:

lang parameter values are uk-UA, ru-RU or en-US depending on what link in my view was clicked. Also I have web config globalization defined section:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="ru-RU" uiCulture="ru-RU" />

启动我的应用程序时,我的语言是预期的俄语,但是当我尝试通过 SetLanguage 操作将语言更改为英语时,视图中的语言没有变化. NavigationMenu.SomeProperty 仍然是俄语.我想念什么?

When my application starts I have Russian language as expected but when I try to change my language with SetLanguage action to English I get no language changes in my views. NavigationMenu.SomeProperty is still Russian. What am I missing?

推荐答案

您将仅更新当前线程的区域性.

You are updating the culture for the current thread only.

大多数站点通过将本地化作为其URL的一部分(在所有页面中)来支持本地化.借助MVC,您可以通过使用动作过滤器处理区域性来实现此方法.此答案为此提供了一个很好的解决方案.

Most sites support localization by including this as part of their URL (in all pages). And with MVC, you can implement this approach by processing the culture using an action filter. This answer has a good solution for this.

除此以外,您还需要通过将区域性持久化到会话或cookie中,然后根据每个请求更新线程的区域性,再次通过实现操作过滤器,或在包含以下内容的应用程序事件中,来实现此目的:请求上下文,例如AquireRequestState.

Aside from this, you would need to implement this by either persisting the culture to the session or a cookie, and then updating the thread's culture on every request, again by implementing an action filter, or during an application event that contains the request context, such as AquireRequestState.

这篇关于如何在ASP .NET MVC中使用Resources和CultureInfo更改网站语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 02:37