I follow the Globalization and localization and Building simple multilingual ASP.NET Core website tutorials to add a language switch for my application.
So, I create
Did you add javascript to make the language selector postback?
(function () {
$("#selectLanguage select").change(function () {
$(this).parent().submit();
});
}());
Did you wire up therequest localization middleware in Configure?
var locOptions= app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
Did you add a method in HomeController like this:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
Add an additional answer for those who did not make it work even if you have updated your code with Joe Auddette's answer.
The CookieOptions
blocked me a long time to make things work:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddYears(1),
IsEssential = true, //critical settings to apply new culture
Path = "/",
HttpOnly = false,
}
);
return LocalRedirect(returnUrl);
}
IsEssential
has following comments in source code:
Indicates if this cookie is essential for the application to function correctly. If true then consent policy checks may be bypassed. The default value is false.
and the consent policy
is set in startup.cs
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies
// is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});