d_ethier
d_ethier

Reputation: 3911

Disable default use of Accept-Language header in ASP.Net Core

In ASP.Net Core, I have the following setup per the documentation on establishing the culture in the application:

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

I've added the Settings:Culture:DefaultRequestCulture to the appsettings.json file so it can be configured on a per site installation basis.

This documentation indicates that the order can be changed, but unfortunately doesn't provide the example on how to do it.

It indicates that these three providers are used by default:

  1. QueryStringRequestCultureProvider
  2. CookieRequestCultureProvider
  3. AcceptLanguageHeaderRequestCultureProvider

I cannot figure out how to disable the third. I want the other ones to remain as is, but for the application to disregard the HTTP header entirely.

Upvotes: 7

Views: 4089

Answers (1)

Tseng
Tseng

Reputation: 64229

Just as you'd like remove any item from an IList<T>.

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

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

Or just

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

Upvotes: 12

Related Questions