我已经为我的 MVC 3 项目实现了语言支持。
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//It's important to check whether session object is ready
if (HttpContext.Current.Session != null)
{
CultureInfo ci = (CultureInfo)this.Session["Culture"];
//Checking first if there is no value in session
//and set default language
//this can happen for first user's request
if (ci == null)
{
//Sets default culture to english invariant
string langName = "en";
//Try to get values from Accept lang HTTP header
if (HttpContext.Current.Request.UserLanguages != null &&
HttpContext.Current.Request.UserLanguages.Length != 0)
{
//Gets accepted list
langName = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
}
ci = new CultureInfo(langName);
this.Session["Culture"] = ci;
}
//Finally setting culture for each request
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
然后我通过这个选择我的语言:
[AllowAnonymous]
public ActionResult ChangeLanguage(string lang, string returnUrl)
{
Session["Culture"] = new CultureInfo(lang);
return Redirect(returnUrl);
}
它在主视图中加载正确的语言,而不是在部分视图中。我错过了什么吗?
谢谢!