asp.net-mvcasp.net-coreblazorasp.net-identityasp.net-core-localization

How to enable to select culture with both url and cookie in asp.net core razor and blazor pages?


I have applied Localization in my asp.net core mvc project. It includes blazor pages for Identity. I want to enable to change the culture by changing the site url's culture part.

domain/en/Home/Index

Currently, the culture can be changed by cookie. This is the cookie culture switch

But when I change the url's culture to ja, the culture isn't changing. How to enable both without any restriction each other?

I added the following code to add culture to the url, but it didn't work for Blazor pages.

app.MapControllerRoute(
    name: "default",
    pattern: "{culture}/{controller=First}/{action=Index}/{id?}"
);

I want to apply this to Blazor pages to. And I added the partial for the culture switch.

<div>
    <form asp-action="CultureManagement" asp-controller="Home" method="post" asp-route-returnUrl="@returnUrl">
        <select name="cultureName" asp-for="@culture!.RequestCulture.UICulture.Name" class="selectpicker" data-width="fit" asp-items="@cultureList"
            onchange="this.form.submit();">
        </select>
    </form>
</div>

It only changes the cookie.

[HttpPost]
public IActionResult CultureManagement(string cultureName, string returnUrl)
{
    Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cultureName)),
        new CookieOptions { Expires = DateTimeOffset.Now.AddDays(30) });
    return LocalRedirect(returnUrl);
}

I want to enable to change culture by changing the url and cookie. And also want to apply to blazor pages.


Solution

  • Change your CultureManagement method like below.

    And make sure your returnUrl is correct when switch to other pages.

        [HttpPost]
        public IActionResult CultureManagement(string cultureName, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cultureName)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(30) }
            );
    
    
            var uri = new Uri(string.Concat(Request.Scheme, "://", Request.Host, returnUrl));
            var pathAndQuery = uri.PathAndQuery;
    
            var newPathAndQuery = Regex.Replace(pathAndQuery, "^/[^/]+", $"/{cultureName}");
    
            return Redirect(newPathAndQuery);
        }
    

    enter image description here

    enter image description here