What is the best way to make an ASP.NET MVC multi language website?
The following code is what I use, but I need to make sure from your real-world experience that my code is the best way for performance to set language in the
Application_AcquireRequestState
method because I noticed that the method get
is called twice in every request.
RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{language}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language = "en-US" }
);
}
Global.asax:
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("language"))
{
var language = (string)HttpContext.Current.Request.RequestContext.RouteData.Values["language"];
if (language != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
}
}
Here are the action links that I use to pass the language parameter:
@Html.ActionLink("English", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "en-US" }, null)
@Html.ActionLink("French", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(),new { language = "fr-FR" },null)