MVC本地化在httpmodule中设置区域性
本文关键字:设置 区域性 httpmodule 本地化 MVC | 更新日期: 2023-09-27 18:20:05
我已经在我的MVC3应用程序上实现了本地化。
我正在寻找一个在ActionFilterAttribute执行之前设置当前区域性的解决方案。
我想从url获取当前的文化:
routes.MapRoute(
"Language",
"{culture}/{controller}/{action}/{id}",
new { culture = "en", controller = "Page", action = "Index", id = UrlParameter.Optional }
);
在基本控制器中,我可以做:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var culture = filterContext.RouteData.Values["culture"] ?? ConfigurationSettings.AppSettings["DefaultCulture"];
var cultureInfo = CultureInfo.GetCultureInfo((string)culture);
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
base.OnActionExecuting(filterContext);
}
我想更新应用程序并在httpmodule 中设置当前区域性
目前我的代码如下:
public void Init(HttpApplication httpApplication)
{
httpApplication.BeginRequest += (sender, eventArgs) =>
{
var defaultCulture = ConfigurationSettings.AppSettings["DefaultCulture"];
CultureInfo cultureInfo = CultureInfo.GetCultureInfo(defaultCulture);
try
{
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
}
catch { }
};
}
如何使用httpmodule中的filterContext.RouteData.Values["culture"]设置当前区域性?
提前感谢您对的任何帮助
Ori
您应该使用自定义路由处理程序来根据路由信息设置区域性。参见以下示例:
public class CultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (requestContext == null)
{
throw new ArgumentNullException("requestContext");
}
string culture = requestContext.RouteData.Values["culture"] as string ?? "";
CultureInfo ci = CreateCultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
return base.GetHttpHandler(requestContext);
}
private CultureInfo CreateCultureInfo(string culture)
{
if (culture == null)
{
throw new ArgumentNullException("culture");
}
CultureInfo ci = null;
try
{
ci = new CultureInfo(culture);
}
catch (CultureNotFoundException)
{
ci = CultureInfo.InvariantCulture;
}
return ci;
}
}