XSS Prevention Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓XSS Prevention runs in O(n) time and O(n) space, in C# as in every other language.
- ✓System.Text.Encodings.Web is the context split, in the framework itself: HtmlEncoder, JavaScriptEncoder and UrlEncoder are three different types with three different escapes, each exposing a Default instance and Encode overloads that write into a TextWriter.
- ✓Let Razor encode. @Html.Raw and new HtmlString on anything non-constant are review blockers unless the sanitiser call is right there in the same expression.
- ✓The C# trap: Setting JsonSerializerOptions.Encoder to JavaScriptEncoder.UnsafeRelaxedJsonEscaping is the standard fix for JSON output littered with escaped angle brackets, and it is documented as unsafe to embed in HTML: it leaves the angle brackets and ampersand alone, so a serialised string containing a closing script tag ends the element you pasted it into.
- ✓TextEncoder exposes a FindFirstCharacterToEncode fast path, so a string with nothing to escape is scanned once and copied as a block rather than character by character, and Razor uses the TextWriter overloads, meaning a rendered page escapes straight into the response buffer with no intermediate string allocated per field.
What XSS Prevention actually is
XSS Prevention in C#: what you actually reach for
C# implementation
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using Ganss.Xss;
// Register once so non-ASCII is not blown up into numeric entities.
builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
static string Link(string url, string label)
{
var ok = Uri.TryCreate(url, UriKind.Absolute, out var u)
&& (u.Scheme == Uri.UriSchemeHttps || u.Scheme == Uri.UriSchemeHttp);
var href = HtmlEncoder.Default.Encode(ok ? url : "#");
return $"<a href=\"{href}\">{HtmlEncoder.Default.Encode(label)}</a>";
}
// JSON into a <script> block: the Default encoder escapes <, > and &.
// UnsafeRelaxedJsonEscaping does not, and a closing script tag inside a
// string then terminates the element.
static string Payload(object o) => JsonSerializer.Serialize(o,
new JsonSerializerOptions { Encoder = JavaScriptEncoder.Default });
static readonly HtmlSanitizer Sanitizer = new(); // AngleSharp DOM per call
static string Bio(string html) => Sanitizer.Sanitize(html);Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for XSS Prevention?
System.Text.Encodings.Web is the context split, in the framework itself: HtmlEncoder, JavaScriptEncoder and UrlEncoder are three different types with three different escapes, each exposing a Default instance and Encode overloads that write into a TextWriter. Razor calls HtmlEncoder on every @expression, IHtmlContent and HtmlString mark a value as already encoded, and @Html.Raw is the explicit opt-out. The older WebUtility.HtmlEncode and HttpUtility.HtmlEncode still exist for the HTML case only. The allowlist sanitiser people reach for is the HtmlSanitizer NuGet package, built on AngleSharp.
What is the most common C# mistake when implementing XSS Prevention?
Setting JsonSerializerOptions.Encoder to JavaScriptEncoder.UnsafeRelaxedJsonEscaping is the standard fix for JSON output littered with escaped angle brackets, and it is documented as unsafe to embed in HTML: it leaves the angle brackets and ampersand alone, so a serialised string containing a closing script tag ends the element you pasted it into. The mirror-image trap is that HtmlEncoder.Default allows only Basic Latin and escapes everything else to numeric entities, so teams swap in HtmlEncoder.Create(UnicodeRanges.All) for readable non-English output and quietly widen what reaches the page unescaped by entity.
How does XSS Prevention actually perform in C#?
TextEncoder exposes a FindFirstCharacterToEncode fast path, so a string with nothing to escape is scanned once and copied as a block rather than character by character, and Razor uses the TextWriter overloads, meaning a rendered page escapes straight into the response buffer with no intermediate string allocated per field. Switching to HtmlEncoder.Create(UnicodeRanges.All) also shortens output substantially for non-Latin text. HtmlSanitizer builds a full AngleSharp DOM per call, so it belongs at write time and cached, never inside a render loop. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.