Prevent XSS in ASP.NET Core: 8 Attacks Tested on .NET 10
Last updated: November 14, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401) and .NET 11.0.0 (SDK 11.0.100), HtmlSanitizer 11.0.26, headless Microsoft Edge 157.0.4341.46, Windows 11
Short answer: to prevent XSS in ASP.NET Core, let Razor encode output with @value, and never pass user input to Html.Raw or MarkupString unless it went through an HTML sanitizer such as HtmlSanitizer first. Razor’s encoding only protects HTML text and quoted attributes. It does not protect values inside <script>, inline event handlers or URLs. For those, serialize with @Json.Serialize(value) and allow-list URL schemes. Then add a nonce-based Content-Security-Policy, which blocked every injected script in my tests. Below, each attack runs against a real app, with the real HTTP response and what a real browser did with it.
The old version of this post explained the theory. This one tests it. I built a small ASP.NET Core app with every common XSS mistake in it, sent the attacks with curl, and loaded each page in headless Edge to see whether the injected code actually ran. Here’s the summary:
| Attack | Does Razor’s encoding stop it? | Fix that worked |
|---|---|---|
<script> in a comment, rendered with @text | Yes | Nothing to fix |
Same comment through Html.Raw or Blazor MarkupString | No, it ran | HtmlSanitizer before Html.Raw |
Value in <script> without quotes, or in a template literal | No, it ran | @Json.Serialize(value) |
| Value in a quoted JS string | Not exploitable here, but it corrupts O'Brien | @Json.Serialize(value) |
Value in an onclick attribute | No, it ran (the browser decodes the entities first) | Don’t build handlers from input; pass data via JSON |
JsonSerializer with UnsafeRelaxedJsonEscaping inside <script> | Not applicable (Html.Raw) | Default encoder or @Json.Serialize |
javascript: URL in href | No, it ran on click | Scheme allow-list with Uri.TryCreate |
Minimal API Results.Content(..., "text/html") | Not involved | HtmlEncoder, or Results.Text / JSON |
| All of the above | Nonce CSP blocked every injected script, handler and javascript: URL |
How I Tested It
The lab is one ASP.NET Core project (XssLab) with Razor Pages, a Blazor static SSR component and minimal API endpoints, plus a console project (Probe) that prints what each encoder and the sanitizer produce. A Python script, run.py, starts the same build three times: plain, with the CSP middleware on, and with a wider Unicode encoder. It sends every attack with curl -s -i and saves the full response. Then it loads the same URL in headless Edge with --dump-dom and saves the DOM after load plus the browser console.
Every payload writes a marker into the page instead of calling alert(), so the DOM dump shows whether it ran. If <body> comes back with data-pwned="...", the attacker’s code executed. Two pages contain a small lab script that calls .click() on a button or link to stand in for a user clicking it. The whole run was repeated on .NET 11 GA. All 31 responses were identical except for the version string.
What Razor’s Default Encoding Does Stop
This is the comment page. Default mode renders the input with @text, raw mode with Html.Raw:
case "raw":
<div id="out">@Html.Raw(text)</div>
break;
case "sanitized":
<div id="out">@Html.Raw(Sanitizer.Sanitize(text))</div>
break;
default:
<div id="out">@text</div>
break;
With @text, the script tag arrives as text:
GET /Comment?text=<script>document.body.dataset.pwned='raw'</script>
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<div id="out"><script>document.body.dataset.pwned='raw'</script></div>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-app-script="ran">
No data-pwned. The page’s own script ran, the injected one didn’t. Razor’s default HtmlEncoder encodes < > & " ' and +, which is enough for element content and for attributes in quotes. The same input in raw mode:
GET /Comment?mode=raw&text=<script>document.body.dataset.pwned='raw'</script>
<div id="out"><script>document.body.dataset.pwned='raw'</script></div>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="raw" data-app-script="ran">
It ran. An <img src=x onerror=...> payload ran too (data-pwned="img"). Search your solution for Html.Raw(, new HtmlString( and MarkupString. Every hit that can see user input is a candidate.
Blazor MarkupString
Blazor has the same split. @Text is encoded, MarkupString is not:
<p id="encoded">@Text</p>
<div id="raw">@((MarkupString)(Text ?? ""))</div>
GET /blazor?text=<img src=x onerror="document.body.dataset.pwned='blazor'">
<body><p id="encoded"><img src=x onerror="document.body.dataset.pwned='blazor'"></p>
<div id="raw"><img src=x onerror="document.body.dataset.pwned='blazor'"></div></body></html>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="blazor">
This component runs in static server-side rendering. I didn’t test interactive Server or WebAssembly mode, where markup is inserted by the Blazor renderer instead of the HTML parser. Treat MarkupString with user input as unsafe in every mode.
Rich Text: Sanitize With HtmlSanitizer
When users are allowed to post HTML (a comment editor, a CMS field), encoding would destroy their formatting. You need a sanitizer that parses the HTML and keeps only an allow-list. HtmlSanitizer (package HtmlSanitizer, namespace Ganss.Xss) 11.0.26 is the current stable release on NuGet. It parses with AngleSharp 1.10.0. I registered it once:
builder.Services.AddSingleton<IHtmlSanitizer>(_ => new HtmlSanitizer());
The sanitized comment page with a mix of good and bad markup:
GET /Comment?mode=sanitized&text=<b>ok</b><img src=x onerror="document.body.dataset.pwned='img'"><script>document.body.dataset.pwned='raw'</script>
<div id="out"><b>ok</b><img src="x"></div>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-app-script="ran">
The <b> survived, the handler and the script didn’t. The Probe project hooks the RemovingTag and RemovingAttribute events, so you can see exactly what the default configuration strips:
IN : <a href="JaVaScRiPt:alert(1)">encoded scheme</a>
removed attribute href="JaVaScRiPt:alert(1)" (NotAllowedUrlValue)
OUT: <a>encoded scheme</a>
IN : <p style="color: red; background-image: url(javascript:alert(1))">styled</p>
OUT: <p style="color: rgba(255, 0, 0, 1)">styled</p>
IN : <iframe src="https://evil.example"></iframe><form action="https://evil.example"><input name="pw"></form>
removed tag <iframe> (NotAllowedTag)
OUT: <form action="https://evil.example"><input name="pw"></form>
IN : <p class="note" id="c1" data-user="7" target="_blank">attributes</p>
removed attribute class="note" (NotAllowedAttribute)
removed attribute id="c1" (NotAllowedAttribute)
removed attribute data-user="7" (NotAllowedAttribute)
OUT: <p target="_blank">attributes</p>
IN : <a href="/relative/page">relative</a> <a href="//evil.example">protocol-relative</a>
OUT: <a href="/relative/page">relative</a> <a href="//evil.example">protocol-relative</a>
Three things surprised me. The default allow-list keeps <form> and <input>. That’s not script execution, but a fake “session expired, log in again” form inside a comment is a phishing kit on your own domain. It also strips class and id, which breaks most editor output. And protocol-relative links to other hosts pass. For a comment box I’d start from this profile:
var strict = new HtmlSanitizer();
foreach (var tag in new[] { "form", "input", "button", "textarea", "select", "option" })
strict.AllowedTags.Remove(tag);
strict.AllowedAttributes.Add("class");
IN : <form action="https://evil.example"><input name="pw"><button>Log in</button></form>
OUT:
IN : <p class="note" id="c1">attributes</p>
OUT: <p class="note">attributes</p>
default AllowedTags count: 99
default AllowedSchemes : https, http
Removing a tag removes its content too, so the “Log in” text disappeared with the form. Sanitize when you render (or both on save and on render), so that a stricter configuration later also applies to old rows.
Values Inside <script>: Where HTML Encoding Fails
This is the mistake I find most often in code reviews: a server value dropped into inline JavaScript. Razor still HTML-encodes it, but the browser doesn’t decode HTML entities inside <script>, and JavaScript has its own dangerous characters. Four variants from the lab page:
<script>var userId = @id;</script>
<script>var userName = '@name';</script>
<script>var userName = `@name`;</script>
<button id="greet" onclick="greet('@name')">Say hi</button>
Unquoted value. The payload needs no < or quote, so the encoder has nothing to encode:
GET /Script?mode=unquoted&id=1;document.body.dataset.pwned=document.domain
<script>var userId = 1;document.body.dataset.pwned=document.domain;</script>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="localhost" data-user-name="(none)">
Template literal. HtmlEncoder leaves backticks, $ and braces alone, as the Probe output shows:
input : <b>"O'Brien" & co</b> `${x}` (1+1) café नमस्ते
HtmlEncoder.Default : <b>"O'Brien" & co</b> `${x}` (1+1) café नमस्ते
GET /Script?mode=template&name=${document.body.dataset.pwned=document.domain}
<script>var userName = `${document.body.dataset.pwned=document.domain}`;</script>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="localhost" data-user-name="localhost">
Quoted string. Here the HTML encoding accidentally holds: the ' becomes ', which is not a quote in JavaScript, so a breakout payload stayed inside the string. But a real name is now wrong:
GET /Script?mode=quoted&name=O'Brien
<script>var userName = 'O'Brien';</script>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-user-name="O&#x27;Brien">
That is the bug that makes people reach for Html.Raw to “fix” it, and that’s when it becomes exploitable.
Event handler attribute. Inside an HTML attribute the browser does decode entities before handing the value to JavaScript, so ' turns back into a quote:
GET /Script?mode=onclick&name=');document.body.dataset.pwned='onclick';//
<button id="greet" onclick="greet('');document.body.dataset.pwned='onclick';//')">Say hi</button>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-greeted="" data-pwned="onclick" data-user-name="(none)">
The encoding looked right in the response and the attack still ran after the (simulated) click.
The Fix: Serialize to JSON
In MVC views and Razor Pages, @Json.Serialize(value) returns a JSON literal that’s safe to place in a script block:
<script>var userId = @Json.Serialize(id); var userName = @Json.Serialize(name);</script>
GET /Script?mode=json&id=1;document.body.dataset.pwned=document.domain&name=</script><script>document.body.dataset.pwned='json'</script>
<script>var userId = "1;document.body.dataset.pwned=document.domain"; var userName = "\u003C/script\u003E\u003Cscript\u003Edocument.body.dataset.pwned=\u0027json\u0027\u003C/script\u003E";</script>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-user-name="</script><script>document.body.dataset.pwned='json'</script>">
The value is always a quoted string, and < > ' " are \u-escaped, so even </script> can’t close the block. The browser got the exact original text back, and O'Brien came through as O'Brien. JavaScriptEncoder.Default.Encode(name) inside quotes also worked (O'Brien</script> came back intact), but you have to remember the quotes. For handlers, don’t build them from input at all. Put the data in a data- attribute (Razor’s attribute encoding is fine there) and attach the handler in a script file.
The UnsafeRelaxedJsonEscaping Trap
People who dislike \u00E9 in their JSON switch to JavaScriptEncoder.UnsafeRelaxedJsonEscaping. The name is accurate:
breakout default : "\u003C/script\u003E\u003Cscript\u003Ealert(1)\u003C/script\u003E"
breakout relaxed : "</script><script>alert(1)</script>"
Rendered with @Html.Raw(JsonSerializer.Serialize(name, relaxed)) inside a script block:
<script>var userName = "</script><script>document.body.dataset.pwned='relaxed'</script>";</script>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="relaxed" data-user-name="(none)">
Worth knowing: minimal APIs already use the relaxed encoder for JSON responses. I checked the registered options on both runtimes:
Encoder is UnsafeRelaxedJsonEscaping: True
That’s fine for an application/json response, since a browser won’t parse it as HTML. It’s not fine if you copy that JSON into a page yourself.
JavaScript URLs in href Attributes
Encoding can’t help with URLs, because javascript:void(...) needs no special characters to be dangerous. A profile page with a “website” field:
<a id="site" href="@url">My website</a>
GET /Link?url=javascript:void(document.body.dataset.pwned='href')
<a id="site" href="javascript:void(document.body.dataset.pwned='href')">My website</a>
--- headless Edge --dump-dom, <html>/<body> after load:
<body data-pwned="href">
The fix is an allow-list of schemes, checked on a parsed absolute URI:
private static readonly string[] AllowedSchemes = ["http", "https", "mailto"];
// Returns the URL only if it is absolute and uses an allowed scheme; otherwise "#".
public static string SafeHref(string? url)
{
if (Uri.TryCreate(url?.Trim(), UriKind.Absolute, out var uri)
&& AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase))
{
return uri.AbsoluteUri;
}
return "#";
}
GET /Link?mode=safe&url=javascript:void(document.body.dataset.pwned='href')
<a id="site" href="#">My website</a>
GET /Link?mode=safe&url= JavaScript:void(document.body.dataset.pwned='href')
<a id="site" href="#">My website</a>
GET /Link?mode=safe&url=https://example.com/u/42?tab=posts
<a id="site" href="https://example.com/u/42?tab=posts">My website</a>
Don’t write a blocklist that checks StartsWith("javascript:"). The leading space and mixed case above would already get around a naive version, and data: and vbscript: exist too. An allow-list doesn’t care what new trick comes along.
Minimal APIs: Results.Content vs Results.Text vs JSON
Minimal APIs have no Razor, so no automatic encoding. These four endpoints return the same input:
app.MapGet("/api/greet/html", (string name) => Results.Content($"<p>Hello {name}</p>", "text/html"));
app.MapGet("/api/greet/encoded", (string name, HtmlEncoder encoder) =>
Results.Content($"<p>Hello {encoder.Encode(name)}</p>", "text/html"));
app.MapGet("/api/greet/text", (string name) => Results.Text($"Hello {name}"));
app.MapGet("/api/greet/json", (string name) => Results.Ok(new { greeting = $"Hello {name}" }));
GET /api/greet/html?name=<script>document.documentElement.dataset.pwned='api'</script>
Content-Type: text/html
<p>Hello <script>document.documentElement.dataset.pwned='api'</script></p>
<html data-pwned="api">
GET /api/greet/encoded?name=<script>document.documentElement.dataset.pwned='api'</script>
<p>Hello <script>document.documentElement.dataset.pwned='api'</script></p>
GET /api/greet/text?name=<script>document.documentElement.dataset.pwned='api'</script>
Content-Type: text/plain; charset=utf-8
Hello <script>document.documentElement.dataset.pwned='api'</script>
GET /api/greet/json?name=<script>document.documentElement.dataset.pwned='api'</script>
Content-Type: application/json; charset=utf-8
{"greeting":"Hello <script>document.documentElement.dataset.pwned='api'</script>"}
Only the text/html endpoint without encoding executed in Edge. The plain-text and JSON responses contain the raw script tag, but Edge displayed them as text. If you build HTML in a minimal API, inject HtmlEncoder and encode every value, or better, return data and let the client render it with textContent. None of the responses had an X-Content-Type-Options: nosniff header. ASP.NET Core doesn’t add one by default. My API security post covers the headers I add to APIs.
Content-Security-Policy With a Nonce
Encoding and sanitizing fix individual bugs. CSP is the layer that saves you from the bug you haven’t found. With a nonce policy, the browser only runs <script> elements that carry this response’s random nonce. It also refuses inline event handlers and javascript: URLs. The middleware:
public sealed class CspNonceMiddleware(RequestDelegate next)
{
public const string ItemKey = "csp-nonce";
public Task Invoke(HttpContext context)
{
var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(16));
context.Items[ItemKey] = nonce;
context.Response.Headers.ContentSecurityPolicy =
$"default-src 'self'; script-src 'nonce-{nonce}'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
return next(context);
}
}
Your own scripts get the nonce from HttpContext.Items:
<script nonce="@Context.Items[CspNonceMiddleware.ItemKey]">document.body.dataset.appScript = 'ran';</script>
The raw comment page again, now on the instance with the middleware switched on. The response still contains the injected script, because CSP doesn’t change the HTML:
Content-Security-Policy: default-src 'self'; script-src 'nonce-EczqohXFaDJhJe/QdhI22A=='; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
<div id="out"><script>document.body.dataset.pwned='raw'</script></div>
<script nonce="EczqohXFaDJhJe/QdhI22A==">document.body.dataset.appScript = 'ran';</script>
In Edge (a separate request, so a different nonce), the app script ran and the injected one was blocked. These are the console messages, trimmed:
<body data-app-script="ran">
"Executing inline script violates the following Content Security Policy directive 'script-src 'nonce-3aolDZd1J5idrVRG0HdLDg==''.
"Executing inline event handler violates the following Content Security Policy directive 'script-src 'nonce-NCq0+ztoEYKXrVmQPlmCkg==''.
"Running the JavaScript URL violates the following Content Security Policy directive 'script-src 'nonce-nRc5ciuUcV8sbF32hMLHiA==''.
Those three lines are the <script> payload, the onerror payload and the javascript: link. None of them set data-pwned. The cost shows up on the script-context page: its inline scripts have no nonce, so CSP blocked them all, including the legitimate ones (two “Executing inline script” errors, and the page did nothing). Adding CSP to an existing app means adding nonces to, or moving out, every inline script and every onclick=. Roll it out with Content-Security-Policy-Report-Only first. Microsoft’s CSP guide for Blazor lists what Blazor’s own scripts need.
Why Razor Turns é and Hindi Text Into &#x…; Entities
A common complaint, and not a security bug. The default encoders only treat Basic Latin as safe and encode everything else:
GET /Unicode?text=café नमस्ते
<p id="literal">Literal in markup: café नमस्ते</p>
<p id="expr">From @ expression: café नमस्ते</p>
<p id="attr" title="café नमस्ते">attribute</p>
Text typed into the .cshtml is sent as-is. Only @ expressions go through the encoder. Browsers display both the same, but the HTML is bigger and harder to read in view-source. To widen the safe list:
builder.Services.Configure<WebEncoderOptions>(o =>
o.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All));
GET /Unicode?text=café नमस्ते
<p id="expr">From @ expression: café नमस्ते</p>
<p id="attr" title="café नमस्ते">attribute</p>
< > & " ' are still encoded with this setting (the Probe line HtmlEncoder (All) shows the same output as the default for those), so it doesn’t weaken XSS protection. The Microsoft XSS docs show the alternative of registering HtmlEncoder.Create(...) with specific ranges. Don’t solve the same complaint in JSON with UnsafeRelaxedJsonEscaping if that JSON ends up inside a page.
.NET 11 GA
I built the same projects for net11.0 with SDK 11.0.100 and ran every curl request again. Comparing all 31 responses (ignoring the Date header and nonces):
31 responses compared, different: version.txt
Encoding, Json.Serialize, the minimal-API JSON encoder and the Unicode behavior are unchanged. HtmlSanitizer 11.0.26 worked on both. I didn’t repeat the Edge runs on .NET 11, since the HTML the browser received was identical.
My XSS Checklist for ASP.NET Core
- Render user data with
@value. Treat everyHtml.Raw,HtmlStringandMarkupStringas a code-review stop. - User HTML goes through one shared, configured
HtmlSanitizer. Remove form tags if you don’t need them. - Never put
@valueinside<script>or anon...attribute. Use@Json.Serializeor adata-attribute. - Run user-supplied URLs through a scheme allow-list before they reach
hreforsrc. - In minimal APIs, return JSON or text. If you must return HTML, encode with the injected
HtmlEncoder. - Add a nonce CSP, start in report-only mode, and remove inline handlers as you go.
- Keep
HttpOnlyon auth cookies so a script that does slip through can’t read them. That limits the damage, it doesn’t prevent XSS.
XSS sits in the injection category with SQL injection. If you’re working through all of them, see SQL injection prevention in C#, OWASP Top 10 for .NET developers and ASP.NET Core security best practices. The OWASP XSS prevention cheat sheet covers more output contexts than this post (CSS, for example).
What I Didn’t Test
- Other browsers. Only headless Edge 157 (Chromium). I didn’t run Firefox or Safari.
- Real clicks. The
onclickandhrefcases use a lab script calling.click()to stand in for a user. - Blazor interactive modes (Server, WebAssembly, Auto). Only static SSR.
- DOM-based XSS in your own JavaScript (
innerHTMLfromlocation.hash), stored XSS through a real database, and CSS or SVG upload contexts. - Mutation XSS and sanitizer bypasses. I ran a handful of classic payloads through HtmlSanitizer, not a fuzzing corpus. Keep the package updated.
- Linux, Docker and Azure. Windows 11 only. The encoders are managed code, so I don’t expect differences, but I didn’t measure it.