skip to content

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%

answer

  1. AddViewLocalization on the MVC builder
  2. resource named after the view's path
  3. LocalizedHtmlString is IHtmlContent
  4. arguments encoded, resource text not
  5. no shared file for IViewLocalizer

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.

solid answer

~40 s

`AddViewLocalization()` on the MVC builder (from `AddControllersWithViews()` or `AddRazorPages()`) calls `AddLocalization` and adds `IHtmlLocalizerFactory`, `IHtmlLocalizer<T>` and `IViewLocalizer`. `IStringLocalizer<T>` returns a `LocalizedString`, which Razor HTML-encodes like any string. `IHtmlLocalizer<T>` and `IViewLocalizer` return `LocalizedHtmlString`, an `IHtmlContent`: the translated text is written as-is, so markup a translator put in the `.resx` renders, while each format argument is HTML-encoded. `IViewLocalizer` derives its resource from the view file: `Views/Cellar/Index.cshtml` in app `WineShop` reads `Resources/Views/Cellar/Index.fr.resx`, and there is no option to point it at a shared file. For strings shared by several views, inject `IHtmlLocalizer<SharedResource>`. Treat `.resx` values as trusted markup and never build keys from user input.

code

razor · 12 lines
razor
@page
@model WineShop.Pages.Cellar.IndexModel
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@inject IHtmlLocalizer<SharedResource> Shared

<h1>@Localizer["Our cellar"]</h1>

@* Resources/Pages/Cellar/Index.fr.resx: "Bon retour, <b>{0}</b> !" *@
<p>@Localizer["Welcome back, <b>{0}</b>!", Model.CustomerName]</p>

<footer>@Shared["Please drink responsibly."]</footer>

go deeper

for a junior

Recall that views inject IViewLocalizer, that it needs AddViewLocalization, and that its .resx mirrors the view's path.

for a middle

Explain the encoding split: LocalizedHtmlString writes the resource text raw and encodes arguments, while LocalizedString is encoded as a whole by Razor.

for a senior

Treat translations as trusted markup: review .resx changes, keep user data in arguments, and choose shared resources through IHtmlLocalizer<T> where IViewLocalizer cannot reach.

for a principal

Set a policy for markup in translations across teams and vendors: text-only resources by default, where HTML is allowed, and how translation changes are reviewed before release.

## Three localizers, two return types | Interface | Resource chosen by | Returns | Razor output | |---|---|---|---| | `IStringLocalizer<T>` | type `T` | `LocalizedString` | whole value HTML-encoded | | `IHtmlLocalizer<T>` | type `T` | `LocalizedHtmlString` | resource text raw, arguments encoded | | `IViewLocalizer` | the executing view's path | `LocalizedHtmlString` | resource text raw, arguments encoded | `IHtmlLocalizer` and `IViewLocalizer` live in `Microsoft.AspNetCore.Mvc.Localization`. Both also expose `GetString(...)`, which returns a plain `LocalizedString` when you want encoded output. ## Registering them `AddLocalization()` alone registers only `IStringLocalizerFactory` and `IStringLocalizer<T>`. The view localizers come from an MVC builder extension: ```csharp builder.Services.AddRazorPages() .AddViewLocalization(o => o.ResourcesPath = "Resources"); ``` `AddViewLocalization` does four things: - calls `AddLocalization` with the options you pass; - registers `IHtmlLocalizerFactory` as a singleton and `IHtmlLocalizer<T>` and `IViewLocalizer` as transients; - adds a `LanguageViewLocationExpander` to the Razor view engine, so a whole view can be translated as a file (`Index.fr.cshtml` with the default `LanguageViewLocationExpanderFormat.Suffix`, or `fr/Index.cshtml` with `SubFolder`); - leaves DataAnnotations alone; `AddDataAnnotationsLocalization` is a separate call, and `AddMvcLocalization` chains both. `HtmlLocalizerFactory` wraps the registered `IStringLocalizerFactory`. The HTML localizers therefore read the same `.resx` files, or the same custom store, as the string localizers. ## How IViewLocalizer finds its resource `ViewLocalizer` is contextualized with the current view before it renders. It takes the executing file path, drops the extension and the leading slash, turns slashes into dots and prefixes the application name: `/Views/Cellar/Index.cshtml` in app `WineShop` becomes base name `WineShop.Views.Cellar.Index`. The factory then applies the root namespace and `ResourcesPath`, so with `"Resources"` the French file is either of: - `Resources/Views/Cellar/Index.fr.resx` - `Resources/Views.Cellar.Index.fr.resx` Without `ResourcesPath`, the `.resx` sits next to the view. A Razor Page works the same way, from `/Pages/...`. Each view has its own resource and `IViewLocalizer` cannot be pointed at a shared file. Strings such as a footer or legal line used across views go into a shared resource read through `IHtmlLocalizer<SharedResource>` or `IStringLocalizer<SharedResource>`. ## What gets encoded `LocalizedHtmlString.WriteTo` formats the resource text through `HtmlFormattableString`. The **format string is written raw** and **each argument is HTML-encoded**. Consider: ```razor <p>@Localizer["Welcome back, <b>{0}</b>!", Model.CustomerName]</p> ``` If the German resource reads `Willkommen zurück, <b>{0}</b>!`, the bold tags render, and a customer named `<script>` appears as text. Three rules follow: 1. **Translations are trusted content.** Whoever edits the `.resx` can inject markup; review translations as you would templates. 2. **User data goes in as arguments**, never concatenated into the key, because a key that is not found is returned as the value and would then be written raw. 3. **Prefer text-only resources.** The documentation's own advice is to localize text, not HTML; keep markup in the view where you can, and use `IHtmlLocalizer` only where a sentence genuinely contains inline markup. ## Choosing the right one - **`IViewLocalizer`** for text that belongs to one view or page and nowhere else. - **`IHtmlLocalizer<SharedResource>`** for shared lines whose translations contain inline markup. - **`IStringLocalizer<T>`**, or `GetString(...)` on either HTML localizer, for HTML attribute values such as `title` or `placeholder` and for strings placed in a script block, where raw markup from a resource is never wanted. Razor writes an `IHtmlContent` raw even inside an attribute, so `@Localizer[...]` there would not encode the translation, while `Localizer.GetString(...)` returns a `LocalizedString` that Razor encodes. ## Blazor and Minimal APIs `IViewLocalizer` depends on MVC's view context, so it is for `.cshtml` views and pages only. Razor components (`.razor`) inject `IStringLocalizer<T>`; a Minimal API has no views and needs only `AddLocalization`. ## Mistakes interviewers listen for - expecting `IViewLocalizer` after `AddLocalization` alone; - expecting a single shared `.resx` behind `IViewLocalizer`; - assuming `IHtmlLocalizer` encodes the resource text, or that it leaves arguments raw; - building a key with string concatenation from request data.

  • A view calls @Localizer["Hello " + Request.Query["name"]]. What is wrong with it?
    The key is built from user input, so it almost never matches a resource entry and the localizer returns the key itself as the value. `IViewLocalizer` writes the resource text without encoding, so the query string reaches the page raw, an XSS hole. Use a constant key with a placeholder and pass the name as an argument, which is encoded.
  • When would you translate a whole view file instead of individual strings?
    When a page is mostly prose, such as terms of sale, and the layout itself differs by language. `AddViewLocalization` registers `LanguageViewLocationExpander`, which looks for `Terms.fr.cshtml` (the default `Suffix` format) or `fr/Terms.cshtml` (`SubFolder`) for the current UI culture before the neutral view.

  • IViewLocalizer encodes the translated text, so markup in a .resx shows as tags.
  • AddLocalization alone is enough to inject IViewLocalizer into a view.
  • IViewLocalizer can be configured to read one shared .resx for every view.
  • IHtmlLocalizer writes format arguments unencoded, so callers must encode user data first.
  • IViewLocalizer is the localizer to inject into Blazor .razor components.