更改区域性时无法使用查询字符串获取 url

Can not get url with query string when changing culture

当我将语言从英语更改为德语时,文化信息 未获取查询字符串。

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中没有查询字符串时,它可以正常工作。但我想 return 那个特定的 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 时,它会创建一个 url,如下所示:

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

尝试像下面这样更改您的 returnUrl :

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

我建议采用以下解决方案,因为当您 url 包含路径库时,accepted 不起作用(例如,当您在 IIS 中使用虚拟路径托管服务时就是这种情况):

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