I would like to know how to set current culture to browser culture by default with ASP.NET Core 1.1.1
I follow this example https://andrewlock.net/adding-localisation-to-an-asp-net-core-application/
In my startup.cs I have this
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IStringLocalizerFactory, SingleFileResourceManagerStringLocalizerFactory>();
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
// Add framework services.
services.AddMvc()
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("es"),
new CultureInfo("fr"),
};
opts.DefaultRequestCulture = new RequestCulture("fr");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
}
And I have a language selector, where I add CookieRequestCultureProvider.DefaultCookieName in the cache.
[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);
}
And this resources files
Resources.resx
Resources.en.resx
Resources.es.resx
Resources.fr.resx
This all works fine, the problem here is, each time I call the web site I want to get the default Culture, in this case "fr", but I get always the last one, I choose before I close the web page.
How can I prevent this happen?
Cookies don't die when the user leaves the website, so because you set the cookie's expiration to be in a year, that last language chosen by the user will be in effect for a year.
Unlike cookies, sessions die when the user leaves the website and someone with the same requirement has already requested that feature on github and created a NuGet package for it.
https://github.com/aspnet/Localization/issues/344
https://www.nuget.org/packages/My.AspNetCore.Localization.Session
Other ways around the issue would be to use a shorter expiration date (if you don't need to be very precise) or to delete the cookie when you detect that the user has created a new session.