MVC Localication在httpmodule中设置文化

时间:2012-01-12 20:57:38

标签: c# asp.net-mvc asp.net-mvc-3 localization

我已经在我的MVC3应用程序上实现了本地化。

我正在寻找在执行ActionFilterAttribute之前设置当前文化的解决方案。

我想从网址获取当前的文化:

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”]设置当前文化?

感谢您提前获取任何帮助

大利

1 个答案:

答案 0 :(得分:1)

您应该使用自定义路由处理程序根据路径信息设置区域性。见下面的例子:

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;
    }
}