Reputation: 125
I have implemented Localization on my MVC3 Application.
i am looking for a solution to setup the current culture before the ActionFilterAttribute is executed.
i would like to get the the current culture from the url:
routes.MapRoute(
"Language",
"{culture}/{controller}/{action}/{id}",
new { culture = "en", controller = "Page", action = "Index", id = UrlParameter.Optional }
);
in the base controller i can do:
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);
}
i would like to update the application and setup the current culture in the httpmodule
at the moment my code looks like this:
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 { }
};
}
how can i setup the current culture using the filterContext.RouteData.Values["culture"] in the httpmodule ?
Thank you in advanced for any help
Ori
Upvotes: 0
Views: 1096
Reputation: 2982
You should use a custom route handler to set the culture accordingly to the route information. See example below:
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;
}
}
Upvotes: 1