Answer the question
In order to leave comments, you need to log in
How to properly organize two languages in asp mvc site?
Hello!
The task is this: to organize two languages, so that the user's automatic language is determined and the required version is issued, and there are no changes in the URL, everything is the same.
Here's what I did:
this is the base controller
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Is it View ?
ViewResultBase view = filterContext.Result as ViewResultBase;
if (view == null) // if not exit
return;
filterContext.HttpContext.Request.UserLanguages[0]; // needs validation return "en-us" as default
string cultureName = "";
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = filterContext.HttpContext.Request.UserLanguages[0];
Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
if (cultureName == "en") { cultureName = "en-US"; }
if (cultureName == "ru") { cultureName = "ru-RU"; }
// Are views implemented separately for this culture? if not exit
bool viewImplemented = CultureHelper.IsViewSeparate(cultureName);
if (viewImplemented == false)
return;
string viewName = view.ViewName;
int i = 0;
if (string.IsNullOrEmpty(viewName))
viewName = filterContext.RouteData.Values["action"] + "." + cultureName; // Index.en-US
else if ((i = viewName.IndexOf('.')) > 0)
{
// contains . like "Index.cshtml"
viewName = viewName.Substring(0, i + 1) + cultureName + viewName.Substring(i);
}
else
viewName += "." + cultureName; // e.g. "Index" ==> "Index.en-Us"
view.ViewName = viewName;
filterContext.Controller.ViewBag._culture = "." + cultureName;
base.OnActionExecuted(filterContext);
}
protected override void ExecuteCore()
{
string cultureName = null;
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = Request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages
// Validate culture name
cultureName = CultureHelper.GetValidCulture(cultureName); // This is safe
// Modify current thread's culture
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureName);
Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureName);
base.ExecuteCore();
}
public ActionResult Index()
{
ViewBag.ClassMain = "active";
return View();
}
Answer the question
In order to leave comments, you need to log in
Take a little out of context
if (cultureName == "en") { cultureName = "en-US"; }
if (cultureName == "ru") { cultureName = "ru-RU"; }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question