skip to content

Cultures & Translations

How ASP.NET Core serves one app in several languages: IStringLocalizer lookups over .resx resources, and request localization that picks each request's culture. Interviewers probe both halves.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

10

In ASP.NET Core 10, what must RequestLocalizationOptions declare before UseRequestLocalization serves French and German, and what happens when you skip it?

level: juniorimportance: must knowfreq 55%

answer

  1. three settings the middleware checks
  2. the lists default to the server's culture
  3. SetDefaultCulture picks the last resort
  4. UseRequestLocalization("en", "fr", "de") shorthand
  5. unsupported cultures logged at Debug

basics

~20 s

RequestLocalizationOptions needs SupportedCultures, SupportedUICultures and a default culture. Both lists default to the server's own culture only, so without them every French or German request is treated as unsupported and served in the server's culture.

solid answer

~40 s

`RequestLocalizationOptions.SupportedCultures` and `SupportedUICultures` start as lists holding only the server's `CultureInfo.CurrentCulture` and `CurrentUICulture`, and `DefaultRequestCulture` is the server's culture too. The middleware accepts a requested culture only if it, or one of its parents, is in those lists. An app that calls `app.UseRequestLocalization()` without configuring them therefore ignores `?culture=fr`, the culture cookie and `Accept-Language: de`, logs "returned the following unsupported cultures" at Debug, and serves the server's culture, which differs between a laptop and a container. Declare them with `SetDefaultCulture("en").AddSupportedCultures(...).AddSupportedUICultures(...)` in `builder.Services.AddRequestLocalization(...)` and call `app.UseRequestLocalization()`, or use the shorthand `app.UseRequestLocalization("en", "fr", "de")`, whose first name becomes the default. The middleware then sets `CultureInfo.CurrentCulture`, `CurrentUICulture` and `IRequestCultureFeature` for the rest of the request.

code

csharp · 21 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLocalization();
builder.Services.AddRequestLocalization(options =>
{
    string[] cultures = ["en", "fr", "de"];
    options.SetDefaultCulture("en")
           .AddSupportedCultures(cultures)
           .AddSupportedUICultures(cultures);
});

var app = builder.Build();
app.UseRequestLocalization(); // reads the options registered above

app.MapGet("/guides/{city}/culture", (string city, HttpContext context) =>
{
    var feature = context.Features.Get<IRequestCultureFeature>()!;
    string source = feature.Provider?.GetType().Name ?? "DefaultRequestCulture";
    return $"{city}: {feature.RequestCulture.UICulture.Name} from {source}";
});

app.Run();

go deeper

for a junior

Recall the three settings, SupportedCultures, SupportedUICultures and the default culture, and that UseRequestLocalization is what sets the culture for a request.

for a middle

Explain the defaults: both lists hold only the server's culture, unsupported names are skipped with a Debug log, and the shorthand overload makes its first name the default.

for a senior

Diagnose an app that is always in one language: the Provider on IRequestCultureFeature, the Debug log, the client's exact culture names and an invariant-globalization container.

for a principal

Decide which cultures a product commits to supporting and how that list is owned and shared between the middleware, language pickers and translation work.

## What the middleware does `UseRequestLocalization()` adds `RequestLocalizationMiddleware`. On every request it: 1. asks each `IRequestCultureProvider` in `RequestCultureProviders` for candidate culture names; 2. accepts a candidate only if it, or a parent culture, appears in `SupportedCultures` (for formatting) or `SupportedUICultures` (for translations); 3. falls back to `DefaultRequestCulture` when no provider produced a supported culture; 4. sets `CultureInfo.CurrentCulture` and `CultureInfo.CurrentUICulture`, which flow through the rest of the request, including across `await`; 5. stores an `IRequestCultureFeature` on `HttpContext.Features`, with the chosen `RequestCulture` and the `Provider` that won (`null` when the default was used). The localizers, the Razor views and culture-sensitive formatting such as `ToString("d")` or `{0:N2}` downstream read those two properties. ## The defaults that bite The options class is safe for a single-language app and silent for a multi-language one: | Property | Default | Effect if left alone | |---|---|---| | `SupportedCultures` | a list with the server's `CultureInfo.CurrentCulture` | every other formatting culture is rejected | | `SupportedUICultures` | a list with the server's `CultureInfo.CurrentUICulture` | every other translation is rejected | | `DefaultRequestCulture` | the server's culture and UI culture | the fallback depends on where the app runs | | `FallBackToParentCultures` / `FallBackToParentUICultures` | `true` | `fr-CA` can match a supported `fr` | | `ApplyCurrentCultureToResponseHeaders` | `false` | no `Content-Language` response header | A travel guide that adds French and German `.resx` files but never declares the cultures works on nobody's machine except by accident: on a developer laptop set to French it seems to work in French, and in a container whose culture is invariant or English it never does. ## Configuring it The usual shape registers the options in DI and adds the middleware without arguments: ```csharp builder.Services.AddRequestLocalization(options => { string[] cultures = ["en", "fr", "de"]; options.SetDefaultCulture("en") .AddSupportedCultures(cultures) .AddSupportedUICultures(cultures); }); app.UseRequestLocalization(); ``` Three details matter: - `AddSupportedCultures` and `AddSupportedUICultures` **replace** the lists; they do not append to the server's culture. - `AddSupportedCultures` does **not** set the default. Only `SetDefaultCulture`, or the shorthand `UseRequestLocalization(params string[] cultures)`, does; the shorthand uses its first name as the default for both culture and UI culture. - `UseRequestLocalization(Action<RequestLocalizationOptions>)` builds a **new** options object that does not come from DI. Code that injects `IOptions<RequestLocalizationOptions>`, such as a language picker listing the supported cultures, then sees the defaults. ## The four UseRequestLocalization overloads | Call | Options come from | Typical use | |---|---|---| | `UseRequestLocalization()` | `IOptions<RequestLocalizationOptions>` in DI | the default; shared with other code | | `UseRequestLocalization(RequestLocalizationOptions)` | the instance you pass | options built by hand | | `UseRequestLocalization(Action<RequestLocalizationOptions>)` | a new instance configured by the action | quick setup, invisible to DI | | `UseRequestLocalization(params string[])` | a new instance: both lists plus `SetDefaultCulture(first)` | samples and small apps | The shorthand throws `ArgumentException` when called with no names, so it cannot silently produce an empty configuration. ## What the rest of the request sees - `CultureInfo.CurrentCulture` and `CurrentUICulture` are set for the request's execution context, so code after an `await` still sees them. - Localizers read `CurrentUICulture` on every lookup; formatting calls read `CurrentCulture`. - `IRequestCultureFeature` is available to any later middleware, filter or handler that needs to know the culture or how it was chosen. ## Diagnosing "it is always English" 1. Read `IRequestCultureFeature.Provider` in a test endpoint: `null` means no provider won and the default applied. 2. Turn on `Debug` logging for `Microsoft.AspNetCore.Localization`: the middleware logs each provider that returned unsupported cultures or UI cultures, with the names it rejected. 3. Compare the supported lists with what the client sent; a browser sending `de-AT` needs `de-AT` or `de` in the list. 4. Check the process's own culture: when nothing is configured, the lists and the default are whatever the process runs in, which in a container is often the invariant culture. ## Mistakes interviewers listen for - believing the middleware supports whatever the browser asks for; - assuming the default is `en-US`, when it is the server's culture; - expecting an unsupported culture to produce an error response, when it is skipped quietly; - calling `AddLocalization` and expecting the request culture to change, when only the middleware sets it.

  • What is the difference between app.UseRequestLocalization(o => ...) and builder.Services.AddRequestLocalization(o => ...) followed by app.UseRequestLocalization()?
    The `Action` overload of `UseRequestLocalization` builds its own options object, outside DI, so only the middleware sees it. `AddRequestLocalization` configures `RequestLocalizationOptions` in DI, which the parameterless `UseRequestLocalization()` reads and any other code can inject, for example a language picker that lists `SupportedUICultures`.
  • The travel guide starts locally but fails at startup with CultureNotFoundException in an Alpine or chiseled container. Why?
    Those runtime-deps images set `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true`, and since .NET 6 creating any culture other than the invariant one in that mode throws `CultureNotFoundException`, which `AddSupportedCultures` and `SetDefaultCulture` do while the middleware's options are built. Use an `-extra` image variant, which ships ICU, and do not set `InvariantGlobalization` in an app that localizes.

  • UseRequestLocalization accepts any culture the browser asks for by default.
  • Without SetDefaultCulture the default request culture is always en-US.
  • An unsupported culture in ?culture= makes the middleware return 400 Bad Request.
  • AddLocalization alone sets the request culture from the Accept-Language header.
  • The first culture passed to AddSupportedCultures automatically becomes the default.

Assumes ASP.NET Core 10 on .NET 10; since .NET 6, creating any culture other than the invariant one in globalization-invariant mode throws CultureNotFoundException.

open as a page

In ASP.NET Core 10, how do AddLocalization and IStringLocalizer<T> return a French or German string, and what comes back when no translation exists?

level: juniorimportance: must knowfreq 62%

basics

~10 s

AddLocalization registers IStringLocalizer<T>, which reads the .resx resources named after T for CultureInfo.CurrentUICulture. Its indexer returns a LocalizedString; when no resource holds the key, Value is the key itself and ResourceNotFound is true.

open as a page

In ASP.NET Core request localization, in what order do the default culture providers run, and when does a provider's answer win?

level: middleimportance: must knowfreq 50%

basics

~10 s

RequestCultureProviders runs QueryStringRequestCultureProvider, CookieRequestCultureProvider, then AcceptLanguageHeaderRequestCultureProvider. The first provider that returns a culture found in the supported lists, directly or through a parent, wins; if none does, DefaultRequestCulture applies.

open as a page

In ASP.NET Core request localization, how do SupportedCultures and SupportedUICultures differ, and when should the two lists hold different cultures?

level: middleimportance: should knowfreq 40%

basics

~10 s

SupportedCultures limits CurrentCulture, which formats dates, numbers and currency and drives culture-aware comparison; SupportedUICultures limits CurrentUICulture, which chooses translated resources. Regional sites list many specific cultures for formatting and a few languages for text.

open as a page

With ASP.NET Core's ResourcesPath set to "Resources", how must a controller's .resx be named, and why might every lookup return the key?

level: middleimportance: should knowfreq 45%

basics

~10 s

The .resx must mirror the type's full name minus the root namespace, under ResourcesPath: Resources/Controllers/CatalogController.fr.resx or Resources/Controllers.CatalogController.fr.resx. A mismatched root namespace, a misplaced marker class or a library type makes the lookup miss silently.

open as a page

In ASP.NET Core MVC and Razor Pages, how do IViewLocalizer and IHtmlLocalizer<T> differ from IStringLocalizer<T>, and what do they HTML-encode?

level: middleimportance: should knowfreq 40%

basics

~20 s

IViewLocalizer and IHtmlLocalizer<T> return LocalizedHtmlString, which Razor writes as HTML: the resource text is not encoded but format arguments are. IViewLocalizer finds its .resx from the view's path; IHtmlLocalizer<T> from a type. Both need AddViewLocalization.

open as a page

On a travel-guide site with URLs like /fr/guides/lisbon, how do you make ASP.NET Core take the culture from that segment first and the cookie second?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Put RouteDataRequestCultureProvider first in RequestCultureProviders, followed by CookieRequestCultureProvider. It reads the culture route value, so routing must have matched an endpoint before UseRequestLocalization runs; URLs without the segment fall through to the cookie.

open as a page

In ASP.NET Core MVC, how does AddDataAnnotationsLocalization translate validation messages, and why does a bare [Required] still render in English?

level: seniorimportance: should knowfreq 35%

basics

~10 s

AddDataAnnotationsLocalization makes MVC look up each attribute's ErrorMessage, and [Display] names, through IStringLocalizer for the model's type. Only an explicit ErrorMessage is a key; a bare [Required] keeps the runtime's built-in English message.

open as a page

How would you serve ASP.NET Core localized strings from a database instead of .resx, and what contract must the IStringLocalizer implementation keep?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Implement IStringLocalizerFactory and IStringLocalizer over the store and register the factory as the singleton IStringLocalizerFactory. Each localizer is per resource, reads CurrentUICulture on every lookup, never throws for a missing key, and serves from a cache, not a query per string.

open as a page