Kiran Joshi
Kiran Joshi

Reputation: 1876

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

Upvotes: 1

Views: 467

Answers (2)

Diego Frehner
Diego Frehner

Reputation: 2560

I would suggest following solution since the accepted does not work when you're url contains a pathbase (which is the case for example when you host your service in IIS in with a virtual path):

returnUrl = UriHelper.BuildRelative(Context.Request.PathBase, Context.Request.Path, Context.Request.QueryString)

Upvotes: 0

Xueli Chen
Xueli Chen

Reputation: 12705

Try change your returnUrl like below :

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

Upvotes: 1

Related Questions