Skip to contentSaltar al contenido
125+ QA and SEO checks per page

XSS Prevention Implementation in C#

14 min readintermediate
Website QA and SEO audits

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

Cross-site scripting is untrusted data reaching a browser parser in a position where that parser accepts it as code rather than as text. The constraint that makes it interesting is that there is no single escape: HTML text, a quoted attribute, an unquoted attribute, a URL scheme, a script block and a style block are six different grammars, and the correct transformation depends entirely on where the value lands, which the code producing the value usually cannot see. That is also why input sanitisation is the wrong layer: at input time you do not yet know the destination context, and you corrupt data that was never HTML. The eight languages diverge because escaping lives in whatever template engine each community adopted rather than in the language itself. Go put a context-aware escaper in its standard library, Python and Rust lean on template packages, the JDK ships none at all, and TypeScript's types are erased before the sink ever runs.

XSS Prevention in C#: what you actually reach for

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.

C# implementation

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. Inside a script block the HTML encoder is the wrong encoder, so JavaScriptEncoder, or a JSON payload read out of a data- attribute, is expected instead. Tag helpers and asp-for are preferred over concatenated markup. Nullable reference annotations are never treated as validation, since they vanish at compile time.
csharp
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 Free

The C#-specific 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. 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.

Performance in C#, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port XSS Prevention between languages.

Real-World Applications

XSS Prevention is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding XSS Prevention helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

XSS Prevention appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose XSS Prevention over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of XSS Prevention to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.