更改区域性时无法获取带有查询字符串的url

时间:2019-12-13 07:23:56

标签: cultureinfo asp.net-core-2.2 asp.net-core-localization

当我将语言从英语更改为德语时,

文化信息未获得查询字符串。

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

当url中没有查询字符串时,它可以正常工作。但是我想返回带有完整查询字符串的特定URL。我写了这样一种设置文化的方法:

    [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>

当我更改lang时,它将创建一个网址,如下所示:

enter image description here

如何获取这样的完整查询字符串:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试如下更改您的returnUrl

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