The Language does not change in the ASP.NET Core Web application

落爺英雄遲暮 提交于 2019-12-07 02:39:27
Joe Audette

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);
}
Dongdong

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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!