我需要实现多语言的asp.nt mvc应用程序,我用以下的httpmodule设置当前的ui线程:
public class CookieLocalizationModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
// eat the cookie (if any) and set the culture
if (HttpContext.Current.Request.Cookies["lang"] != null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
string lang = cookie.Value;
var culture = new System.Globalization.CultureInfo(lang == "en" ? "en-US" : "tr-TR");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}
我在Global.asax的Session_Start()方法上设置语言cookie,因为我需要根据请求url主机设置不同的语言cookie(我在mvc应用程序中有多个站点)
当在context_BeginRequest()方法中首次启动应用程序时,cookie值为null,因此未正确设置线程文化。
我应该在哪里设置默认cookie(我需要查看url主机)?
答案 0 :(得分:0)
您第一次可以从 HTTP标头获取语言。这是代码片段 公共类BaseController:Controller { protected override IAsyncResult BeginExecuteCore(AsyncCallback callback,object state) { string cultureName = null;
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ?
Request.UserLanguages[0] : // obtain it from HTTP header AcceptLanguages
null;
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}}
我也管理多语言网站,我在URL路由中定义语言(例如websitename / en / Home / Index)
您也可以参考这篇文章,解释有关多语言网站的所有内容。
我希望这会对你有所帮助。
由于