- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Speaking the User's Language in ASP.NET Core
An online retailer runs a small order-status and support portal used by customers across North America, Europe, and Asia. Support tickets keep arriving complaining that prices, dates, and error messages show up in the wrong language or format no matter what the customer's browser is set to, and the order-status messages the portal builds outside a web request were written without any thought to locale at all. You are the developer tasked with fixing the portal's localization end to end: read the customer's real language preference, apply it consistently through the request pipeline, translate and format content safely with fallbacks, and make sure the pages and the status messages agree on what language to show.
Lab Info
Table of Contents
-
Challenge
Step 1: Orientation to the Portal's Localization Gap
The retailer's order-support portal works fine for one kind of customer: someone in the United States, reading English, paying in dollars, expecting dates as month/day/year. Every other customer is filing tickets. A shopper in Madrid sees prices rendered as "$1234.5" instead of "1.234,50 €". A customer in Tokyo gets validation errors in English no matter what their browser is set to. And the order-status messages the portal builds in a background job, written last sprint without anyone thinking about locale, show different text than the page, sometimes the wrong language entirely, because no request is there to say which language the customer wants. None of this is because the retailer's developers don't know C# or ASP.NET Core; it's because localization is a pipeline, not a single setting. A request arrives carrying a language preference in its Accept-Language header. That preference has to be parsed, validated against the languages the portal actually supports, and carried through middleware to every controller and view that renders text. Resource files have to be organized so translations can be found and safely degrade when a key is missing. Validation messages, formatted currency, and formatted dates all need to agree with whatever culture was negotiated, and so does any text built outside a request, such as a status message from a background job. Over the next four steps you'll build this pipeline end to end, in the order a request actually flows through it. Step 2 builds a standalone catalog that turns a raw locale string or Accept-Language header into one of the portal's supported cultures. Step 3 wires that catalog into ASP.NET Core's request localization middleware, including a custom provider for an explicit override. Step 4 builds safe formatting and localizer helpers that never crash or leak a raw resource key. Step 5 finishes by localizing the order form's validation and making the order-status message agree with the rest of the portal even when it's built outside a request. Step 6 then runs the finished portal so you can watch it all work together.
-
Challenge
Step 2: Interpret Locale Identifiers and Match Browser Languages
Every later step in this lab depends on being able to answer one question reliably: given some string a browser or a query parameter handed us, which of the portal's supported cultures does it mean?
CultureInfoaccepts many real cultures the portal has no translations for, and throws aCultureNotFoundExceptionon malformed strings that aren't locale identifiers at all. The catalog insrc/CultureCatalog.csis where that gets sorted out once, so nothing downstream has to re-litigate it. Normalizing a single locale string is only half the job: a browser's Accept-Language header lists several, in preference order, each with an optional quality weight likeen-US,es;q=0.8,fr;q=0.5. The catalog needs to walk that list and hand back the first entry that's actually one of the portal's supported cultures. To keep this lab focused on parsing and validation, it simplifies by assuming the header is already written in priority order, so it strips the weights without reading them. Real headers aren't guaranteed to be sorted (fr;q=0.5,en;q=0.9lists the lower-priority language first), andq=0means "not acceptable". A production implementation would sort by weight and dropq=0entries, or use ASP.NET Core'sAcceptLanguageHeaderRequestCultureProvider, which Step 3 uses for the real pipeline. -
Challenge
Step 3: Configure Culture Middleware and Provider Priority
With the catalog able to normalize any locale string, the next question is how ASP.NET Core learns which culture to use for a given request.
RequestLocalizationOptionsholds the list of cultures the app supports and a default to fall back to;UseRequestLocalizationreads it on every request and sets the current thread's culture before your controllers or views run. Getting the supported list right here matters: keepSupportedCulturesandSupportedUICulturesidentical. The middleware only skips a provider's result when both the culture and the UI culture are unsupported; if just one is missing, that one silently falls back to the default, leaving the request with a mismatched culture and UI culture. The Accept-Language header is a good default signal, but the portal's support agents need to force a specific culture while reproducing a customer's ticket, without changing their own browser settings. ASP.NET Core lets you plug in your ownIRequestCultureProvideralongside the built-in ones:src/QueryStringCultureProvider.csis where that override lives, reading alangquery-string value and normalizing it through the catalog you just built. ASP.NET Core also ships aQueryStringRequestCultureProviderwith a configurable key, so a custom provider isn't the only option; this lab writes its own because the built-in one doesn't pass the value throughCultureCatalog.NormalizeLocale, and the portal'slangkey is a support-team convention. A request can carry signals from more than one provider at once (alangoverride and an Accept-Language header both present at the same time), andRequestLocalizationOptions.RequestCultureProvidersis checked in list order, with the first non-null result whose culture is supported winning (a result for an unsupported culture is passed over and the next provider gets a turn). That means the override you just wrote is useless if it isn't placed ahead of the header-based provider. -
Challenge
Step 4: Format Output and Localize Safely
With the right culture reliably attached to every request, the portal needs something to say in it. It keeps its translations in
.resxresource files, one set per culture, looked up throughIStringLocalizerfor plain text andIHtmlLocalizerfor text that's allowed to contain markup. Currency and dates don't go through resource files at all: they're formatted directly from aCultureInfo, which is wheresrc/PriceFormatter.cscomes in. Dates behave the same way currency does: the format string stays fixed, but the culture passed alongside it changes everything from separator characters to whether the month or day comes first. The same fallback discipline applies: an order's date has to render as something readable even if the culture attached to the request turns out to be oneCultureInfodoesn't recognize. Translations inevitably fall behind the English resource file: a new error message ships in English before the Spanish.resxfile catches up.IHtmlLocalizerdoesn't throw when a key is missing; it quietly returns the key itself as the rendered text, which is exactly the kind of raw, unfriendly string that should never reach a customer.src/SafeLocalizer.cswraps the real localizer so every caller gets either the translation or a deliberate fallback, never the bare key. When a message has placeholders, such as a customer's name,IHtmlLocalizeralso HTML-encodes the values you pass in, soGetSafeHtmlforwards them to the localizer rather than building the string itself. -
Challenge
Step 5: Localize Validation and Status Messages
The order form's validation still speaks only English, which is the last place the portal's English-only past shows through in server-rendered pages.
src/OrderValidation.csholds the quantity check the form calls into; the fix isn't a new rule, it's making the existing rule report its failure through the sameIStringLocalizerpipeline as everything else, so the error matches whatever culture the request negotiated back in Step 3. The order-status message is where the request pipeline stops helping. Inside a request,CultureInfo.CurrentUICultureis already set by the same request localization middleware that handles every other page. A message built by a background job, such as a shipping notification, has no request for that middleware to run on, so the ambient culture can be invariant (for example with invariant globalization, or when the job never sets a culture). As a lab simplification, the builder treats an invariant ambient culture as "nobody set one" and falls back to the culture the caller passes in asfallbackCultureName, such as the customer's stored language preference.src/StatusMessageBuilder.csis where that gap gets closed. With a culture that's correct whether or not a request is running, the status message's actual text can finally be assembled the same way the rest of the page assembles its own: a resource lookup for the words, and the price and date formatters from Step 4 for anything that needs locale-specific formatting rather than translation. -
Challenge
Step 6: See One Order in Every Customer's Language
Every task is done and graded. Now see them work together on one sample order.
src/Program.csserves it at/orderand renders it in whatever culture the request negotiates. Its translations come from a small in-memory table that stands in for the portal's.resxfiles.Start the portal
Use two terminal tabs. In the first Terminal tab, start the portal and leave it running:
dotnet run --project src/Lab.csprojWhen the output shows
Now listening on: http://0.0.0.0:5000, the portal is ready. Startup errors appear in this tab.Switch to the second Terminal tab for every
curlcommand in this step. Check that the portal answers:curl -s localhost:5000 -w '\n'It prints
Order Support Portal. ### One order, two browsersAsk for the same order as a German browser, then as a Canadian French one:
curl -s -H "Accept-Language: de-DE" localhost:5000/order curl -s -H "Accept-Language: fr-CA,fr-FR;q=0.8" localhost:5000/orderThe German customer sees
Total: 1.234,50 €andOrdered: Dienstag, 5. März 2024. The French customer sees1 234,50 €andmardi 5 mars 2024. Both come from the samedecimaland the sameDateTime, passed through yourFormatPriceandFormatOrderDatefrom Step 4. The€in both totals comes from the culture, not from a currency conversion: the amount is the same number either way, and a real portal would format with the order's own fixed currency.The second header leads with
fr-CA, which isn't in your catalog, so the middleware skips it and settles onCulture: fr-FR. That is your Task 3.1 options at work: only a culture in your supported list can win. TheStatus:line is the order-status message from yourFormatStatusMessage(Task 5.3). The words come from theOrderStatustemplate and the date fromFormatOrderDate, so the message matches the rest of the page. ### A support agent's override beats the browserKeep the German browser header, but add the
langoverride a support agent would use, first with a real culture and then with garbage:curl -s -H "Accept-Language: de-DE" "localhost:5000/order?lang=ja-JP" curl -s -H "Accept-Language: de-DE" "localhost:5000/order?lang=xx-YY"The first response comes back as
Culture: ja-JPwithOrdered: 2024年3月5日火曜日, even though the browser asked for German. YourQueryStringCultureProvider(Task 3.2) answered first because yourConfigureProviderOrder(Task 3.3) put it ahead of the header provider. TheTotal:line reads¥1,235: formatting changes how an amount is written, not which currency it is in, and yen have no decimal places.The second response is a normal English page,
Culture: en-US, not an error.xx-YYisn't a culture the portal supports, so yourNormalizeLocale(Task 2.1) turned it into the default before the middleware ever saw it. ### Errors and missing text in the customer's languageSubmit an invalid quantity as a Spanish customer:
curl -s -H "Accept-Language: es-ES" "localhost:5000/order?quantity=0"The last line reads
Quantity: La cantidad debe ser al menos 1.YourValidateQuantity(Task 5.1) looked upQuantityTooLowthroughIStringLocalizerinstead of returning an English sentence. Change the request toquantity=3and it readsQuantity: 3 accepted.Now look at the
Notice:line. ItsHolidayHourskey has no text in any culture yet. A plainIHtmlLocalizerwould show the customer the bare key,HolidayHours. YourSafeLocalizer(Task 4.3) sawIsResourceNotFoundand printedSupport hours may change over the holidays.instead. TheBanner:line above it goes through the same method and found its translation:Envío gratuito en todos los pedidos.When you're finished, go back to the first Terminal tab and press
Ctrl+Cto stop the portal.To rerun every check, use
dotnet test tests/Lab.Tests.csproj --nologo --verbosity quiet. The portal now reads each customer's real language preference, lets an agent override it safely, and renders prices, dates, errors, and status messages to match.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.