禁用ASP.Net Core中默认使用Accept-Language标头

时间:2016-11-13 02:15:57

标签: asp.net .net asp.net-mvc asp.net-core .net-core

在ASP.Net Core中,我根据在应用程序中建立文化的文档进行了以下设置:

var supportedCultures = new[]
{
  new CultureInfo("en-CA"),
  new CultureInfo("fr-CA"),
  new CultureInfo("fr"),
  new CultureInfo("en"),
  new CultureInfo("en-US"),
};

var defaultRequestCulture = Configuration["Settings:Culture:DefaultRequestCulture"];

if (defaultRequestCulture == null)
{ 
  defaultRequestCulture = "en-CA";
}

app.UseRequestLocalization(new RequestLocalizationOptions
{
  DefaultRequestCulture = new RequestCulture(defaultRequestCulture),
  SupportedCultures = supportedCultures,
  SupportedUICultures = supportedCultures
});

我已将Settings:Culture:DefaultRequestCulture添加到appsettings.json文件中,因此可以按站点安装进行配置。

This documentation表示订单可以更改,但遗憾的是没有提供有关如何执行此操作的示例。

它表示默认使用这三个提供程序:

  1. QueryStringRequestCultureProvider
  2. CookieRequestCultureProvider
  3. AcceptLanguageHeaderRequestCultureProvider
  4. 我无法弄清楚如何禁用第三个。我希望其他的保持不变,但是应用程序完全忽略了HTTP标头。

1 个答案:

答案 0 :(得分:4)

就像您要删除IList<T>中的任何项目一样。

var localizationOptions = new RequestLocalizationOptions
{
    SupportedCultures = ...,
    SupportedUICultures = ...,
    DefaultRequestCulture = new RequestCulture("en-US")
};

var requestProvider = localizationOptions.RequestCultureProviders.OfType<AcceptLanguageHeaderRequestCultureProvider>().First();
localizationOptions.RequestCultureProviders.Remove(requestProvider);

或者只是

var localizationOptions = new RequestLocalizationOptions
{
    SupportedCultures = ...,
    SupportedUICultures = ...,
    DefaultRequestCulture = new RequestCulture("en-US"),
    RequestCultureProviders = new List<IRequestCultureProvider>
    {
        // Order is important, its in which order they will be evaluated
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    };
};