I am new in c# mvc, and I'm trying to make a multi language website, now so far I've been reading the best practice is work with resources or files resx and to set the language o culture in a cookie variable, but my question is how do I set the culture to a cookie automatically? I mean
if A person goes to the website for first time; how di I globally detect the pc or browser language and set the culture to that language detected for every future action the person will make on the website, also store it in a cookie variable due to if the person change the language and visit the website again,the website initializes with the language that the person chose.
so far I've got this:
global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpCookie language = HttpContext.Current.Request.Cookies["CultureInfo"];
if (language != null && language.Value != null)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language.Value);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language.Value);
}
else
{
Thread.CurrentThread.CurrentCulture = someWayToDetectThePcOrBrowserLanguage;
Thread.CurrentThread.CurrentUICulture = someWayToDetectThePcOrBrowserLanguage;
}
}
the someWayToDetectThePcOrBrowserLanguage method I don't have it, I'm looking for a way to do that. And once done that if the person is form a english country the url looks like this:
www.website.com/en/
if the person is from a spanish country looks like this:
www.website.com/es/
and so goes on for some more languages.
now to change the language I have this for the html:
<form id="languages" method="get">
<select name="selectLanguages" id="selectLanguages>
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
my jquery is this one:
$('#selectLanguages').on('change', function () {
var id = $(this).val();
$.ajax({
type: 'GET',
url: '/Language/ChangeCulture',
data: { lang: id },
success: function (e) {
}
})
})
finally the function is this one:
public void ChangeCulture(string lang)
{
Response.Cookies.Remove("CultureInfo");
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["CultureInfo"];
if (languageCookie == null) languageCookie = new HttpCookie("CultureInfo");
languageCookie.Value = lang;
languageCookie.Expires = DateTime.Now.AddDays(10);
Response.SetCookie(languageCookie);
Response.Redirect(Request.UrlReferrer.ToString());
}
from this point on, I'm totally lost, if you can help me, this intends to change the url from this www.website.com/AutoDetectedLanguage/ to this www.website.com/anotherLanguage/
And also for every future action stay in the selected or detected culture e.g
www.website.com/en/controller/action
or
www.website.com/en/anotherController/anotherAction
if language changes
www.website.com/es/sameController/sameAction