Skip to content

Localize request UI culture in Cratis Arc

Arc can choose the UI culture for each HTTP request while keeping number and date formatting invariant. This is opt-in. Without ArcOptions.Localization, Arc does not negotiate a culture or add a Content-Language header.

using Cratis.Arc;
var builder = WebApplication.CreateBuilder(args);
builder.AddCratisArc(configureOptions: options =>
{
options.Localization = new()
{
SupportedUICultures = ["en", "nb-NO"],
DefaultUICulture = "en"
};
});
var app = builder.Build();
app.UseCratisArc();
await app.RunAsync();

You can also set Cratis:Arc:Localization in configuration:

{
"Cratis": {
"Arc": {
"Localization": {
"SupportedUICultures": ["en", "nb-NO"],
"DefaultUICulture": "en"
}
}
}
}

Use distinct, canonical .NET culture names, such as nb-NO, and include the default in the supported list. Invalid options stop startup. Formatting uses CultureInfo.InvariantCulture unless you set FormattingCulture to a canonical culture name. Even then, that culture is fixed for every request: a client’s language never selects a formatting culture or a time zone. JSON formats still follow the serializer’s contract.

Create the client’s locale store from its generated localization policy. Run cratis-l10n check --server path/to/appsettings.json to check that the frontend and server policies agree. Development builds of the Arc client warn when a response’s Content-Language does not match the requested language or when setLocale receives an unsupported tag. See localization in React for the full setup.

By default Arc reads only Accept-Language, in descending quality (q) order with header order breaking ties. It skips malformed entries and uses q=0 to exclude languages unless a more specific positive range applies. A positive wildcard selects the default or the first non-excluded language in configured order. Arc considers up to 32 header entries and ignores headers larger than 8 KiB. If all languages are excluded, Arc still uses DefaultUICulture rather than returning 406.

Arc ignores language-tag extensions and private-use suffixes for UI matching. It tries an exact match (case-insensitive), an explicit alias, a supported parent, then a unique descendant of the original tag after aliasing. For example, nb can select nb-NO, but fr-CA cannot select fr-FR.

To let the Norwegian no preference select Bokmål, add "Aliases": { "no": "nb-NO" } under Cratis:Arc:Localization (or set Aliases = new Dictionary<string, string> { ["no"] = "nb-NO" } in C#). In the frontend’s localization.json, set "aliases": { "no": "nb-NO" }, using nb instead if that’s the supported frontend tag. When no is neither supported nor aliased, cratis-l10n add nb and cratis-l10n add nb-NO add this explicit frontend alias, and cratis-l10n check warns if Bokmål is already supported. The CLI does not modify the server configuration. An exactly supported no still wins, and this alias does not cover Nynorsk (nn).

For explicit overrides, set Providers to a nonempty list in priority order, for example ["QueryString", "Cookie", "AcceptLanguage"]. In C#, the identifiers are members of Cratis.Arc.Localization.RequestCultureProvider. An unsupported value falls through to the next provider.

Provider Request value
QueryString The ui-culture parameter, for example ?ui-culture=nb-NO.
Cookie The .AspNetCore.Culture cookie, for example c%3Den%7Cuic%3Dnb-NO. Arc uses uic (or c if uic is empty) for UI culture only, not formatting.
AcceptLanguage The Accept-Language header.

The Arc client uses the reserved _cratisUiCulture query parameter on observable-query WebSocket and SSE URLs because browser stream APIs cannot set Accept-Language. When localization is enabled, one valid hint that resolves to a supported culture takes precedence on the handshake. Invalid, unmatched, and repeated hints fall through to the configured providers. Arc ignores the hint on requests that do not look like a handshake. When Arc cannot tell whether an endpoint streams, it falls back to the host’s WebSocket handshake signal or a GET accepting text/event-stream. Custom request adapters can supply a single stream hint through their existing query dictionary. If your app uses ASP.NET Core WebSocket middleware, install UseWebSockets() before request localization so Arc can recognize the handshake. The parameter does not bind as a query argument.

Arc sends the selected Content-Language, sets Vary: Accept-Language when that provider is enabled, and prevents caches from storing responses when the cookie provider is enabled.

UseCratisArc() installs localization before Arc endpoints. If earlier middleware or non-Arc routes need the culture, call app.UseCratisRequestLocalization() before them. A later UseCratisArc() call won’t install it twice. Use this in place of the invariant request middleware or any other request localization middleware; do not run two policies in the same pipeline.

During the request, the selection becomes CultureInfo.CurrentUICulture. FluentValidation’s built-in messages use that culture unless the application overrides FluentValidation’s language. For app-specific messages, let .NET find the localized .resx resources at validation time:

RuleFor(command => command.Name)
.NotEmpty()
.WithMessage(_ => ValidationMessages.NameRequired);

Passing a lambda keeps a shared validator from resolving the message before the request culture is known. The request’s UI and formatting cultures are restored when it ends. Arc does not change the host’s default thread cultures. For the self-hosted HTTP listener, see Request localization in Arc.Core.

Give an authored validation refusal a full application catalog ID so the client can render it in the current UI language. On the server, keep fallback prose in Message, and keep the rule’s identity in Reason and ReasonDetail. For example, a command that returns a validation refusal can return:

using Cratis.Arc.Validation;
static ValidationResult SeatsUnavailable(int remaining) =>
ValidationResult.Error($"Seats remaining: {remaining}.", ["SeatCount"], reasonDetail: "SeatLimit") with
{
MessageId = "booking.seatsRemaining",
MessageArguments = new Dictionary<string, object> { ["count"] = remaining }
};

A custom FluentValidation rule can opt in with .WithArcMessage(...) from Cratis.Arc.Validation. Keep .WithMessage(...) for fallback prose and pass optional caller state to WithArcMessage rather than chaining a second WithState. For example, inside a validator whose model has a SeatCount property:

const int remaining = 3;
RuleFor(booking => booking.SeatCount)
.Must(count => count <= remaining)
.WithMessage($"Seats remaining: {remaining}.")
.WithArcMessage("booking.seatsRemaining", new Dictionary<string, object> { ["count"] = remaining });