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

前端 未结 2 464
悲哀的现实
悲哀的现实 2021-01-14 07:49

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

相关标签:
2条回答
  • 2021-01-14 08:05

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 08:07

    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;
    });
    
    0 讨论(0)
提交回复
热议问题