In a Razor view, what does @ HTML-encode by default, and when do Html.Raw, HtmlString or MarkupString open an XSS hole?
answer
- strings in, entities out
- IHtmlContent skips the encoder
- who wrote the markup?
- script blocks are a different context
basics
~20 sRazor HTML-encodes every @ value unless it is IHtmlContent; Html.Raw and HtmlString in views, or MarkupString in components, write markup unencoded, so applied to user-supplied text such as a customer note they let injected script run.
solid answer
~40 sWhen Razor writes an `@` value it checks the type. A string is HTML-encoded, so `<script>` in a customer note goes out as `<script>`. Any other non-`IHtmlContent` value is converted with `ToString()` and encoded. An `IHtmlContent` value is written as it is, and that is the opt-out: `Html.Raw(value)` simply wraps the string in an `HtmlString`; components use `MarkupString`. Raw output is safe only for markup you control, such as a constant or reviewed resource text, or HTML passed through a real sanitizer. On the customer's own note it is a stored XSS hole. Encoding is also for HTML contexts only: inside a `<script>` block an encoded value is wrong, so pass data through a `data-` attribute or `Json.Serialize`.
code
razor · 14 lines@{
// Typed by the customer at checkout: untrusted.
var customerNote = "<script>alert(1)</script>";
var customerName = "José O'Brien";
// A constant the team wrote and reviewed: trusted.
const string thanksHtml = "<em>Thanks for your order!</em>";
}
<p>Note: @customerNote</p>
<p title="@customerName">@customerName</p>
<p>@Html.Raw(thanksHtml)</p>
<div id="order" data-note="@customerNote"></div>
<script>
var note = @Json.Serialize(customerNote);
</script>go deeper
Remember that @ HTML-encodes strings and that Html.Raw, HtmlString and MarkupString switch that off.
Explain the rule in Write: IHtmlContent goes out as is, everything else is converted to a string and encoded, including non-ASCII characters by default.
Review raw output by asking who wrote the markup, sanitize rich text before Html.Raw, and move script data through data- attributes or Json.Serialize.
Make raw-output calls a review gate: each Html.Raw or MarkupString must name a trusted source or a sanitizer, and the team owns one sanitizer policy.
## What Razor does with every `@` value When a Razor view writes the result of an expression such as `@customerNote`, the generated code calls the view's `Write(object)` method. In ASP.NET Core 10's source that method checks the value's type: 1. `null` writes nothing; 2. a value that implements **`IHtmlContent`** is written as it is, through its own `WriteTo`; 3. anything else is turned into a string with `ToString()` and passed through the view's **`HtmlEncoder`** before it is written. So **encoding is the default** for strings, numbers and your own types alike. A customer note containing `<script>alert(1)</script>` is rendered as `<script>alert(1)</script>`, which the browser shows as text. The same encoder runs for values inside attributes, so `title="@customerName"` is safe for quotes as well. ## What the default encoder changes The encoder replaces characters that could break out of text or an attribute: `<`, `>`, `&`, `"` and `'` become entities. It also encodes every character **outside the Basic Latin range** by default, which surprises people: `José` is written as `José`. Browsers display it correctly, but the page source is harder to read and larger. To widen the safe list, register an encoder built with `HtmlEncoder.Create` and the extra `UnicodeRanges` in the service container; that changes only encoders taken from dependency injection, which is what Razor uses. ## The escape hatches: `IHtmlContent` and friends Every way of writing markup unencoded goes through the same door, a value Razor trusts to be HTML already: | API | Where | What it does | |---|---|---| | `Html.Raw(value)` | MVC views and Razor Pages | Returns `new HtmlString(value)`; written unencoded | | `HtmlString` | Any code producing view output | An `IHtmlContent` holding a string that is already HTML | | `IHtmlContent` results | Helpers and tag helpers | Written through `WriteTo`; the helper is responsible for its own encoding | | `MarkupString` | Razor components (`.razor`) | Rendered as HTML or SVG instead of a text node | The XSS guidance in the docs is blunt: `HtmlString` should never be combined with untrusted input, and raw HTML built from any untrusted source should always be avoided in components. ## When raw output is a hole Raw output is safe when **you know who wrote the markup**: - a constant or resource string the team wrote and reviewed; - HTML produced by your own code from already-encoded parts; - user-supplied rich text that has passed a dedicated HTML sanitizer configured with an allow-list. It is a stored XSS hole when the value came from a user and was not sanitized: the order note, a display name, a product review, or a database column that an attacker might have written. The docs count data from your own database as untrusted for exactly that reason. A common anti-pattern is `Html.Raw(note.Replace("\n", "<br>"))`: the line breaks become markup, and so does everything else in the note. Encode first, then add your own tags. ## HTML encoding is for HTML contexts Razor's encoder targets HTML text and attributes. Inside a `<script>` block the browser does not decode entities, so `var who = '@customerName';` produces `'O'Brien'`: wrong data, and HTML encoding is not the escaping JavaScript needs. The safe patterns are: - put the value in a `data-` attribute (encoded normally) and read it from script; - emit it with `@Json.Serialize(value)`, which returns JSON as an `IHtmlContent` serialized with `JavaScriptEncoder.Default`, so `<` becomes `\u003C`. ## Where encoding happens, and where it does not It helps to separate three moments in a value's life: 1. **Input**: the customer types a note and the app stores it as typed. Validation can reject obviously bad input, but the docs warn never to rely on validation alone. 2. **Storage**: the database holds the raw text. Storing it pre-encoded makes it hard to search or reuse outside HTML, and invites double encoding later. 3. **Output**: Razor encodes at the moment of writing, for the HTML context it writes into. That is the one place the protection is reliable, which is why every `Html.Raw` that skips it needs a stated reason. ## Habits that keep a view safe - Let `@` do the encoding; never pre-encode and store encoded text, because encoding belongs at output. - Do not wrap `Html.Encode(...)` in `@`: it returns a plain string, so the view encodes it a second time. - Treat every `Html.Raw`, `HtmlString` and `MarkupString` in review as a claim that must name its trusted source. - Prefer formatting in markup over building HTML strings in C#.
- A Razor view must show a customer's rich-text note with bold and links; how do you render it safely?Do not call `Html.Raw` on the stored text. Either keep the note as plain text and let `@` encode it, or store a restricted format such as Markdown and render it with a library that escapes input, or pass the HTML through a dedicated sanitizer with an allow-list of tags and attributes before wrapping the result in `Html.Raw`. The raw call must always follow a step you trust.
- Why does a Razor view write José as José, and how do you change it?By default the HTML encoder only treats the Basic Latin range as safe and writes every other character as a numeric reference. Browsers display it correctly, but the source is noisier. Register an `HtmlEncoder` created with `HtmlEncoder.Create` and the extra `UnicodeRanges` you need; only encoders taken from dependency injection, which Razor uses, pick it up.
- How should a Razor view pass a server value into an inline script?Not with `'@value'` inside the script: the view applies HTML encoding, which JavaScript does not decode, so the data is wrong and the escaping is not JavaScript escaping. Put the value in a `data-` attribute and read it from the DOM, or write `@Json.Serialize(value)`, which emits JSON escaped with the JavaScript encoder.
Html.Raw is like a mailroom stamp reading 'already inspected': the mailroom then forwards the parcel without scanning it, which is fine for parcels your own staff packed and dangerous on a parcel a stranger handed in.
- Razor writes @ values raw unless you call Html.Encode yourself.
- Html.Raw is safe once the input passed model validation.
- Data read from our own database is trusted, so Html.Raw on it is fine.
- HTML-encoded output with @ is safe inside a script block too.
- Wrapping Html.Encode in @ is the safe way to print user input.
- MarkupString in a component sanitizes the HTML it renders.