MVC 4的多语言应用程序
本文关键字:语言 应用程序 MVC | 更新日期: 2023-09-27 18:23:54
我在做这个多语言MVC 4 web应用程序时遇到了一点麻烦,我到处都找过了,但没有找到我想要的东西。
我想要的是:我的解决方案分为4个项目,其中有web MVC 4项目(主项目)和一个Resource项目,我在其中创建了2个资源文件(en-US.resx和pt-BR.resx)
@using Resources
@{
ViewBag.Title = pt_BR.HomeTitle;
}
我唯一想知道的是,如何将资源文件(pt_BR和en_US)存储在某个文件中,并且文本将被转换,比如这个
var culture = Resources.en_US; //or var culture = Resources.pt_BR;
然后
@using Resources
@{
ViewBag.Title = culture.HomeTitle;
}
然后我将使用我在应用程序的开头选择的文件中的资源字符串
你可以做的是为英语文本创建一个Home.resx文件,为葡萄牙语文本创建Home.pt-BR.resx档案,然后像这个一样访问它们
@{
ViewBag.Title = Resources.Home.Title;
}
线程的区域性将选择正确的文件。您可以在web.config中手动设置线程区域性。例如
<globalization uiCulture="pt-BR" culture="pt-BR" />
除了terjetyl提到的内容外,为了能够更改区域性,您还需要为控制器添加额外的功能。
首先,您需要创建以下类(您可以将其放置在Controllers文件夹中):
public class BaseController : Controller
{
protected override void ExecuteCore()
{
string cultureName = null;
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
// If there is a cookie already with the language, use the value for the translation, else uses the default language configured.
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
{
cultureName = ConfigurationManager.AppSettings["DefaultCultureName"];
cultureCookie = new HttpCookie("_culture");
cultureCookie.HttpOnly = false; // Not accessible by JS.
cultureCookie.Expires = DateTime.Now.AddYears(1);
}
// Validates the culture name.
cultureName = CultureHelper.GetImplementedCulture(cultureName);
// Sets the new language to the cookie.
cultureCookie.Value = cultureName;
// Sets the cookie on the response.
Response.Cookies.Add(cultureCookie);
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
base.ExecuteCore();
}
}
然后,您需要使MVC项目上的每个控制器都从创建的类继承。
之后,您需要在Views文件夹的Web.config上的namespaces标记上添加以下代码。
<add namespace="complete assembly name of the resources project"/>
最后,您需要在更改语言的按钮上添加将"_culture"cookie设置为正确语言代码的说明。
如果你有任何问题,请告诉我。