liveBook · Manning

HTML escaping

As explained in ASP.NET Core in Action, 3e

HTML encoding is the transformation of characters in text into representations that browsers treat as literal content rather than markup or executable code.

HTML escaping transforms text before it reaches a page, so characters such as markup delimiters appear as literal content instead of becoming HTML. Razor automatically HTML-encodes C# expressions, primarily to prevent users from injecting malicious data or JavaScript. section 17.3.3 section 29.1

Use HTML escaping as the safe default when writing values into Razor-rendered HTML:

  • Render ordinary C# expressions with Razor’s default behavior; encoded tags such as <strong> remain visible as text. section 17.3.3
  • Treat user-submitted names and other stored input as unsafe unless they are encoded when rendered. section 29.1
  • Avoid Html.Raw for user input; it writes strings directly without encoding and can execute injected scripts. section 17.3.3 section 29.1
  • When creating a Tag Helper, encode output before SetHtmlContent(), or pass unencoded input to SetContent() for automatic encoding. section 32.1.1

Displaying a task containing markup

Given task = "<strong>Check oil</strong>", ordinary Razor output produces visible text such as "<strong>Check oil</strong>" because the markup is encoded. Using @Html.Raw(task) instead produces bold text, but creates a security risk when the value is user-controlled. section 17.3.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains automatic Razor encoding, Html.Raw risks, JavaScript encoding differences, and Tag Helper output APIs.
Examples
Uses a task containing <strong> markup, injected script tags, JavaScript variables, and a SystemInfoTagHelper.
What it assumes
Assumes familiarity with Razor expressions and HTML output, while explaining the security reason for encoding from the rendering examples.
What you can do after
Apply it via Razor’s default output encoding and safe Tag Helper APIs while recognizing when raw output creates an XSS vulnerability.
How it connects
Ties HTML escaping to Razor templates, cross-site scripting, JavaScript encoding, HtmlEncoder, and Tag Helpers.

Also explained in

Compare how 3 books explain HTML escaping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.