7

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.

1 Answer 1

12

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()
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! The first approach worked for me provided that the Startup.cs had the System.Linq dependency using System.Linq;. I preferred the second one for the succinct nature, but the IRequestCultureProvider interface was not available and I couldn't track down the dependency for that.
IRequestCultureProvider is part of the Microsoft.AspNetCore.Localization package and is in the namespace of the same name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.