如何在MVC 4中获取当前区域性或浏览器语言。
我找到了一些从HttpContext和HttpRequest获取的示例,但这在MVC 4上不起作用。
在MVC 4上要如何实现呢?
如何在MVC 4中获取当前区域性或浏览器语言。
我找到了一些从HttpContext和HttpRequest获取的示例,但这在MVC 4上不起作用。
在MVC 4上要如何实现呢?
UserLanguages
属性:public ActionResult SomeAction()
{
string[] userLanguages = Request.UserLanguages;
...
}
Accept-Languages
请求头,则此属性的值将为 null。因此,在访问其值之前,请确保检查它不为 null,以避免出现 NREs。 /// <summary>
/// Extensions on <see cref="HttpRequest"/> and <see cref="HttpRequestBase"/>
/// </summary>
public static class HttpRequestExtensions
{
/// <summary>
/// Retrieve culture of client.
/// </summary>
/// <param name="request">Current request.</param>
/// <returns><c>null</c> if not to be determined.</returns>
public static CultureInfo DetermineClientCulture(this HttpRequest request)
{
return DetermineClientCulture(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieve culture of client.
/// </summary>
/// <param name="request">Current request.</param>
/// <returns><c>null</c> if not to be determined.</returns>
public static CultureInfo DetermineClientCulture(this HttpRequestBase request)
{
if (request == null)
{
return null;
}
string[] languages = request.UserLanguages;
if (languages == null)
{
return null;
}
//first try parse of full langcodes. Stop with first success.
foreach (string language in languages)
{
string lang = language.ToLowerInvariant().Trim();
try
{
return CultureInfo.GetCultureInfo(lang);
}
catch (CultureNotFoundException)
{
}
}
//try parse again with first 2 chars. Stop with first success.
foreach (string language in languages)
{
string lang = language.ToLowerInvariant().Trim();
if (lang.Length > 2)
{
string lang2 = lang.Substring(0, 2);
try
{
return CultureInfo.GetCultureInfo(lang2);
}
catch (CultureNotFoundException)
{
}
}
}
return null;
}
}
用法:
/// <summary>
/// Called before the action method is invoked.
/// </summary>
/// <param name="filterContext">Information about the current request and action.</param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.IsChildAction)
{
//no need to do the hassle for a child action
//set the culture from the request headers
var clientCulture = Request.DetermineClientCulture();
if (clientCulture != null)
{
//and/or CurrentUICulture
Thread.CurrentThread.CurrentCulture = clientCulture;
}
}
base.OnActionExecuting(filterContext);
}
UserLanguages
属性返回一个字符串数组的原因。 - Darin Dimitrov