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?
answer
- not in the default provider list
- Insert(0, ...) or AddInitialRequestCultureProvider
- route value key culture
- route values exist only after routing
- segment-less URLs fall through
basics
~10 sPut 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.
solid answer
~40 s`RouteDataRequestCultureProvider`, in `Microsoft.AspNetCore.Localization.Routing`, reads the `culture` and `ui-culture` route values (`RouteDataStringKey`, `UIRouteDataStringKey`). It is not one of the three default providers, so insert it at index 0, with `Insert(0, ...)` or `AddInitialRequestCultureProvider`. For "segment, then cookie" also remove the query string provider, or rebuild the list as route, cookie, Accept-Language. The provider calls `GetRouteValue`, which has a value only after endpoint routing has matched: `WebApplication` adds `UseRouting` at the start of the pipeline when you do not call it, but an explicit `app.UseRouting()` placed after `app.UseRequestLocalization()` leaves the provider blind, and the cookie or header decides every time. A URL without the segment makes the provider return `null`, so the cookie and then the header decide. An unsupported segment such as `/xx/` is logged at Debug and skipped, not rejected.
code
csharp · 25 linesusing System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Localization.Routing;
builder.Services.AddRequestLocalization(options =>
{
string[] cultures = ["en", "fr", "pt"];
options.SetDefaultCulture("en").AddSupportedCultures(cultures).AddSupportedUICultures(cultures);
options.RequestCultureProviders.Clear();
options.RequestCultureProviders.Add(new RouteDataRequestCultureProvider()); // 1. /fr/...
options.RequestCultureProviders.Add(new CookieRequestCultureProvider()); // 2. saved choice
options.RequestCultureProviders.Add(new AcceptLanguageHeaderRequestCultureProvider()); // 3. browser
});
var app = builder.Build();
app.UseRouting(); // route values must exist before the provider reads them
app.UseRequestLocalization();
var guides = app.MapGroup("/{culture}/guides");
guides.MapGet("/{city}", (string city) =>
$"{city} in {CultureInfo.CurrentUICulture.Name}");
app.MapGet("/guides/{city}", (string city) => // no segment: cookie, then header
$"{city} in {CultureInfo.CurrentUICulture.Name}");go deeper
Recall that a culture in the URL needs RouteDataRequestCultureProvider and that it must be placed first in the provider list.
Explain the culture route key, why routing must have matched before the middleware runs, and what happens on URLs without the segment.
Diagnose a segment that is ignored: explicit UseRouting order, a mismatched route parameter name, unsupported values falling through, and a switcher that only sets the cookie.
Decide whether the URL, a cookie or a profile owns the language for public and signed-in pages, and how canonical URLs per language are kept consistent.
## Why the default list ignores the URL The three default providers read the query string, the culture cookie and `Accept-Language`. A culture carried in the path, `/fr/guides/lisbon`, is invisible to them. ASP.NET Core ships a fourth provider for it, `RouteDataRequestCultureProvider`, in the `Microsoft.AspNetCore.Localization.Routing` namespace. It reads two route values: - `RouteDataStringKey`, default `"culture"`; - `UIRouteDataStringKey`, default `"ui-culture"`; when only one is present it is used for both. The route template must therefore name its parameter `culture`, or the key must be changed to match. ## Wiring the provider For a travel guide where the URL decides first and a saved choice second, rebuild the list explicitly: ```csharp options.RequestCultureProviders.Clear(); options.RequestCultureProviders.Add(new RouteDataRequestCultureProvider()); options.RequestCultureProviders.Add(new CookieRequestCultureProvider()); options.RequestCultureProviders.Add(new AcceptLanguageHeaderRequestCultureProvider()); ``` `options.AddInitialRequestCultureProvider(new RouteDataRequestCultureProvider())` is the shorter route to "segment first", but it keeps the query string provider in second place, ahead of the cookie. ## Routing must run first `RouteDataRequestCultureProvider` calls `HttpContext.GetRouteValue`. Route values are filled in by the routing middleware when it matches an endpoint. Before that, the call returns `null` and the provider reports nothing. - In a `WebApplication` that never calls `UseRouting`, the framework inserts it at the **start** of the pipeline, so the values exist when request localization runs. - An explicit `app.UseRouting()` written **after** `app.UseRequestLocalization()` breaks this: the provider always sees `null`, and the cookie or header silently decides. - A request that matches no endpoint, such as a static file or a 404, has no route values either. ## What happens on each kind of URL | URL | Route provider | Outcome | |---|---|---| | `/fr/guides/lisbon` | returns `fr` | `fr`, if supported | | `/pt/guides/lisbon` with `pt` unsupported | returns `pt` | logged at Debug, cookie then header decide | | `/de-CH/guides/zurich` with `de` supported | returns `de-CH` | `de` through parent fallback | | `/guides/lisbon`, another endpoint without the segment | returns `null` | cookie, then header, then default | An unsupported segment is **not** a 404. The page renders in whatever culture the later providers choose, under a URL that claims another language. Constraining the route parameter to the supported names is a routing decision made in the template. ## Keeping the cookie in second place The cookie's job on this site is to remember a choice for URLs that do not carry one, such as the home page or an API call. Two consequences: 1. A language switcher must **redirect to the URL with the new segment**; writing the cookie alone changes nothing on a page whose URL says `/fr/`. 2. The home page `/` can redirect to `/{culture}/` using the culture the cookie or header produced, so every content page carries its language in the URL. ## Diagnosing an ignored segment 1. Echo `IRequestCultureFeature.Provider` from a test endpoint: if it is the cookie or header provider, the route provider returned nothing or an unsupported value. 2. Check that the route parameter is literally named `culture`, or that `RouteDataStringKey` was changed to match, for example `new RouteDataRequestCultureProvider { RouteDataStringKey = "lang", UIRouteDataStringKey = "lang" }`. 3. Check the order of `UseRouting` and `UseRequestLocalization` in `Program.cs`. 4. Check that the value is in the supported lists; the Debug log names rejected values. 5. Check that the request matched an endpoint at all. ## In MVC only for some controllers When only part of an MVC app uses the segment, `[MiddlewareFilter<T>]` can run a request localization pipeline as a filter on those controllers, after routing has matched, instead of globally. ## Mistakes interviewers listen for - assuming the route provider is in the default list; - appending it at the end, where the cookie and header answer first; - calling `UseRouting` after `UseRequestLocalization`; - expecting an unsupported segment to return 404; - a language switcher that sets only the cookie.
- Why does the route provider see no culture when app.UseRouting() is called after app.UseRequestLocalization()?Route values are set by the routing middleware when it matches an endpoint. Running before it, `GetRouteValue("culture")` returns `null`, so `RouteDataRequestCultureProvider` returns `null` and the cookie or header decides. `WebApplication` adds `UseRouting` at the start only when you never call it yourself; an explicit call fixes its position.
- How do /fr/guides/lisbon and /guides/lisbon coexist, and which culture does the second get?Map both endpoints. On `/guides/lisbon` there is no `culture` route value, so the route provider returns `null` and the cookie, then `Accept-Language`, then the default decide. Many sites redirect such URLs to the segment form so each page has one canonical address per language.
- RouteDataRequestCultureProvider is one of the default request culture providers.
- Adding the route provider at the end of the list makes the URL segment win.
- The route provider parses the path itself, so routing order is irrelevant.
- An unsupported segment such as /pt/ makes request localization return 404.
- Setting the culture cookie is enough to switch a page whose URL carries /fr/.