How do you build an ASP.NET Core language switcher that remembers the visitor's choice with CookieRequestCultureProvider.MakeCookieValue?
answer
- .AspNetCore.Culture is the default name
- c=fr|uic=fr
- validate against the supported list
- LocalRedirect back to returnUrl
- takes effect on the next request
basics
~10 sAppend the .AspNetCore.Culture cookie with CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), which writes c=fr|uic=fr, after checking the culture is supported, then redirect locally. CookieRequestCultureProvider reads it on the following requests.
solid answer
~40 sA switcher is a POST action that receives the chosen culture and a return URL. It first checks the value against `SupportedUICultures` from the injected `IOptions<RequestLocalizationOptions>`, because `new RequestCulture(culture)` creates a `CultureInfo` and throws `CultureNotFoundException` for a name the platform cannot create. It then calls `Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), options)`: the name is `.AspNetCore.Culture` and the value `c=fr|uic=fr`, escaped on the wire. Give it an `Expires` so it outlives the browser session and, under a consent policy, `IsEssential = true`. Finish with `LocalRedirect(returnUrl)`. The choice applies from the next request, because this request's culture was already set. Providers above the cookie still win: a `?culture=` link, and a route segment if one is configured.
code
csharp · 18 linespublic sealed class LanguageController(IOptions<RequestLocalizationOptions> localization) : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Set(string culture, string returnUrl)
{
bool supported = localization.Value.SupportedUICultures!
.Any(c => string.Equals(c.Name, culture, StringComparison.OrdinalIgnoreCase));
if (!supported) return BadRequest();
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName, // .AspNetCore.Culture
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), // c=pt|uic=pt
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true });
return LocalRedirect(returnUrl);
}
}go deeper
Recall the default cookie name, that MakeCookieValue builds the value, and that the switcher posts the choice and redirects back.
Explain the c=|uic= format, why the culture is validated first, why the change shows only after the redirect, and which providers still outrank the cookie.
Harden the switcher: antiforgery on the POST, LocalRedirect, Expires and IsEssential under consent, and the interaction with route segments or a profile-based provider.
Decide where a visitor's language preference lives, cookie, URL or account, and how the choice follows a user across devices and sign-in.
## What the cookie provider expects `CookieRequestCultureProvider` is second in the default provider list. It reads one cookie: - the name is `CookieName`, default `CookieRequestCultureProvider.DefaultCookieName`, which is `".AspNetCore.Culture"`; - the value is two parts separated by `|`: `c=` for the culture and `uic=` for the UI culture, for example `c=fr-CH|uic=fr`. `CookieRequestCultureProvider.MakeCookieValue(RequestCulture)` writes that format, and `ParseCookieValue(string)` reads it. Anything else, such as a bare `fr`, parses to `null`, and the provider is skipped as if the cookie were absent. If one part is empty, the other is used for both. ## The switcher, step by step 1. **Receive** the culture and a return URL from a small form in the layout, posted with an antiforgery token. 2. **Validate** the culture against `SupportedUICultures`. Inject `IOptions<RequestLocalizationOptions>`; this sees the real lists only when they were registered in DI with `AddRequestLocalization` (or `Configure<RequestLocalizationOptions>`), not built inline by `UseRequestLocalization(Action<...>)`. 3. **Build** the value with `MakeCookieValue(new RequestCulture(culture))`. Validation first matters: the `RequestCulture(string)` constructor creates a `CultureInfo`, which throws `CultureNotFoundException` for a name the platform cannot create. 4. **Append** the cookie with `Response.Cookies.Append`. The value is escaped with `Uri.EscapeDataString`, so the header shows `c%3Dfr%7Cuic%3Dfr`; reading it back unescapes it. 5. **Redirect** with `LocalRedirect(returnUrl)`, which refuses absolute URLs to other hosts, so the switcher cannot be used as an open redirect. ## Cookie options worth setting | Option | Why | |---|---| | `Expires` | without it the cookie is a session cookie and the choice is lost when the browser closes | | `IsEssential = true` | with a cookie consent policy, non-essential cookies are not written before consent | | `Path` | default `"/"`, which is what a site-wide preference needs | ## When does the new language appear? Request localization runs early in the pipeline. By the time the switcher action executes, `CultureInfo.CurrentUICulture` for **this** request is fixed, so a page rendered in the same response would still use the old language. The redirect starts a new request, which carries the new cookie, and the cookie provider applies it. ## Providers that still outrank the cookie - **The query string provider** comes first by default, so a shared link with `?culture=pt` shows Portuguese for that request without changing the saved cookie. - **A route-segment provider**, if the site uses `/fr/...` URLs, must be first, so the switcher has to redirect to the URL with the new segment; the cookie then covers pages without one. - **A custom provider** reading a signed-in user's profile may sit first as well; then the switcher also updates the profile. ## Rendering the picker The layout lists the supported cultures from the same options the middleware uses and posts the choice: ```razor @inject IOptions<RequestLocalizationOptions> Localization @{ var current = Context.Features.Get<IRequestCultureFeature>()!.RequestCulture.UICulture; } <form asp-controller="Language" asp-action="Set" method="post"> <input type="hidden" name="returnUrl" value="@($"{Context.Request.Path}{Context.Request.QueryString}")" /> <select name="culture" onchange="this.form.submit()"> @foreach (var c in Localization.Value.SupportedUICultures!) { <option value="@c.Name" selected="@(c.Name == current.Name)">@c.NativeName</option> } </select> </form> ``` The form tag helper adds the antiforgery token to a POST form, `NativeName` shows each language in its own name, and reading `IRequestCultureFeature` marks the language currently in effect. ## Mistakes interviewers listen for - writing the bare culture name as the cookie value; - passing unchecked input to `new RequestCulture(...)`; - redirecting with `Redirect(returnUrl)`; - expecting the current response to change language; - forgetting `Expires`, so the choice disappears with the browser session.
- The visitor picks Portuguese, but /fr/guides/porto still renders in French. Why?The site's route-segment provider runs before the cookie provider, and the URL still says `fr`. The cookie is correct but never consulted for that URL. The switcher must redirect to `/pt/guides/porto`, rewriting the segment in the return URL, and keep the cookie for pages without a segment.
- What happens if some other code writes the culture cookie as just "pt"?`CookieRequestCultureProvider.ParseCookieValue` expects two `|`-separated parts starting with `c=` and `uic=`. A bare `pt` parses to `null`, so the provider reports nothing and `Accept-Language` or the default decides. Always produce the value with `MakeCookieValue`.
- The culture cookie's value is simply the culture name, such as pt.
- Appending the cookie changes the culture of the response being rendered now.
- new RequestCulture(culture) quietly ignores a culture name it cannot create.
- A saved culture cookie overrides a ?culture= query string by default.
- Redirect(returnUrl) is safe because returnUrl comes from our own form.