这里有一个很好的主题: Get CultureInfo from current visitor
解释我们可以使用以下方式轻松获取浏览器语言:
var userLanguages = Request.UserLanguages;
这里的问题是,这只给了我在浏览器中配置的语言,但没有给出我选择的语言。同时,数组中的第一种语言([0])可能不是活动语言。
有没有办法在服务器端找到活动的?我知道我可以使用javascript在客户端进行,但我想避免双重调用。
答案 0 :(得分:2)
您需要通过Cookie设置此信息(可以通过页面上的设置切换)。
public ActionResult SetCulture(string culture) //culture is something like en-US, you can validate it ahead of time.
{
HttpCookie cookie = Request.Cookies["currentCulture"];
if (cookie != null)
cookie.Value = culture; // update cookie value
else //create the cookie here
{
cookie = new HttpCookie("currentCulture");
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
return Redirect(Request.UrlReferrer.ToString()); //send them back to the site they were at (in a translated form).
}
要确定服务器端的文化,只需在执行操作时读取cookie。
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
HttpCookie cultureCookie = Request.Cookies["currentCulture"];
string cultureName = cultureCookie== null ? "en-US" : cultureCookie.Value;
if (cultureCookie != null)
cultureName = cultureCookie.Value;
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}