我刚刚开始本地化ASP.NET MVC应用程序。大多数字符串将在资源文件中定义,并通过马特的本地化助手。其他字符串必须存储在数据库中。

我的问题: 我应该在请求管道的早期设置 CurrentUICulture 并在整个应用程序中使用它,或者在需要时直接使用 Request.UserLanguages [0] 吗?

现在我想我应该在Application_BeginRequest 中设置 CurrentUICulture 。实现看起来像这样:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var cultureName = HttpContext.Current.Request.UserLanguages[0];
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
}

这是设置 CurrentUICulture 的最佳位置, Request.UserLanguages [0] 是获取该信息的最佳位置吗?


<强>更新

Ariel的帖子显示,无需代码即可使用 web.config 定义

<system.web>
  <!--If enableClientBasedCulture is true, ASP.NET can set the UI culture and culture for a Web page automatically, based on the values that are sent by a browser.-->
  <globalization enableClientBasedCulture="true" culture="auto:en-US" uiCulture="auto:en"/>
有帮助吗?

解决方案

以下是使用HttpModule的示例:

http://weblogs.manas .com.ar / smedina / 2008/12/17 / internationalization-in-aspnet-mvc /

其他选项,创建一个基本Controller类并在那里实现本地化逻辑。 或者使用动作过滤器属性,但您必须记住在每个控制器上添加它或将此方法与基本Controller类组合。

其他提示

Request.UserLanguages [0]只能提示用户希望看到的语言。大多数用户不知道在哪里更改浏览器语言。

另一点:不确定Request.UserLanguages [0]是否是有效语言。它甚至可以为空。 (不确定那里有什么机器人)

您通常在页面上有语言选择器。一旦用户在那里选择了语言,它就存储在cookie,会话或URL中。我喜欢使用url,因为我认为它看起来很漂亮。

如果用户未在页面上设置语言而看到您的页面,则应检查Request.UserLanguages [0]是否为您支持的语言,并设置Thread.CurrentThread.CurrentUICulture。

我使用过滤器来设置Thread.CurrentThread.CurrentUICulture。好吧,只要没有其他过滤器使用Thread.CurrentThread.CurrentUICulture。否则,您需要为过滤器设置正确的执行顺序。

我也使用Matts助手,到目前为止效果非常好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top