cultureinfoasp.net-core-2.2asp.net-core-localization

Can not get url with query string when changing culture


Culture info is not get query string when I change a language from English to German.

Startup.cs

 services.Configure<RequestLocalizationOptions>(options =>
          {
                    var supportedCultures = new[]
                    {
                                new CultureInfo("de-DE"),
                                new CultureInfo("en-US"),
                    };
                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                options.RequestCultureProviders = new List<IRequestCultureProvider>
            {
                new QueryStringRequestCultureProvider(),
                new CookieRequestCultureProvider()
            };
        });

It works properly when there is no query string in url. But I want to return that particular url with full query string. I wrote a method to set culture 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);
    }

_Layout.cshtml

 <form id="selectLanguage" asp-controller="Home"
       asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
       method="post" class="form-horizontal" role="form">
     <select name="culture" onchange="this.form.submit();"
             asp-for="@requestCulture.RequestCulture.UICulture.Name" 
             asp-items="cultureItems">
     </select>
 </form>

When I'm changing the lang, then it creates a url as shown here:

enter image description here

How can I get full query string like this:

enter image description here


Solution

  • Try change your returnUrl like below :

    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value+Context.Request.QueryString.Value}";