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

HTML Sanitizer 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 your Web Development question into a ready to paste AI prompt, free →

Key Takeaways

  • ✓HTML Sanitizer runs in O(n) time and O(n) space, in C# as in every other language.
  • ✓Encoding ships in the box: System.Net.WebUtility.HtmlEncode, and System.Text.Encodings.Web.HtmlEncoder with HtmlEncoder.Create(UnicodeRanges.All) when you need finer control over which ranges survive.
  • ✓Return IHtmlContent, in practice an HtmlString, rather than a bare string. Razor encodes an @expr automatically unless the value implements IHtmlContent, so this makes sanitizer output the one thing that renders raw and removes the reason for @Html.Raw at every call site.
  • ✓The C# trap: System.Text.Json escapes <, >, &, ' and + by default, specifically so that serialised output is safe to embed inside a script element.
  • ✓AngleSharp allocates a managed object per node and per attribute, so a normal fragment produces gen0 garbage that server GC reclaims cheaply; the case worth measuring is the multi-megabyte document that lives long enough to be promoted.

What HTML Sanitizer actually is

An HTML sanitizer takes markup from somewhere you do not control and returns markup you are willing to put on a page. Exactly one design survives contact with real input: parse the string with a genuine HTML parser, walk the tree it produces, keep only the elements and attributes named on an allowlist, and serialise what is left. Shortcuts around that fail for structural reasons. Matching tags with a regular expression fails because HTML is not a regular language and browsers recover aggressively from garbage: an unterminated attribute value, a missing closing bracket, a stray second angle bracket all still produce elements. A denylist fails because the set of dangerous names grows with every browser release while the set of harmless ones does not. Three hazards then survive a naive allowlist. URL-bearing attributes carry their own mini-language, so href and src need a scheme decision: javascript: executes on activation, data: can smuggle an entire document, and legacy vbscript: is still on payload lists, while https: and mailto: are inert. Foreign content breaks the assumption that a tag name identifies an element, because inside svg or math the names a, title and style parse under different rules. And mutation XSS appears when a sanitized tree is serialised and parsed again, since the second parse can build a different tree from the first, turning inert output live with nothing added. The eight languages diverge hard here. Two get a spec-compliant parser free from the platform they already run on. One ships a tokenizer with no tree at all, so the open-element stack is yours to carry. Five have no HTML parser in the standard library and route you to one well-known package. One expresses the trust boundary in types and then erases it before anything runs. One will hand your walker a counterfeit attribute list. And in one, deleting a node mid-walk quietly ends the walk.

HTML Sanitizer in C#: what you actually reach for

Encoding ships in the box: System.Net.WebUtility.HtmlEncode, and System.Text.Encodings.Web.HtmlEncoder with HtmlEncoder.Create(UnicodeRanges.All) when you need finer control over which ranges survive. Parsing does not: System.Xml.XmlReader wants well-formed XML. The spec-compliant HTML5 parser is AngleSharp, whose AngleSharp.Html.Parser.HtmlParser.ParseDocument returns an IHtmlDocument of IElement nodes carrying LocalName, NamespaceUri, Attributes and RemoveAttribute; the prebuilt allowlist sanitizer Ganss.Xss.HtmlSanitizer sits on top of it. Razor's own contract is Microsoft.AspNetCore.Html.IHtmlContent.

C# implementation

Return IHtmlContent, in practice an HtmlString, rather than a bare string. Razor encodes an @expr automatically unless the value implements IHtmlContent, so this makes sanitizer output the one thing that renders raw and removes the reason for @Html.Raw at every call site. Give every allowlist collection StringComparer.Ordinal anyway, even though Dictionary/HashSet already default to ordinal equality: an explicit comparer documents intent and survives a future refactor to a culture-sensitive comparer elsewhere in the same file. Snapshot with ToList() before removing anything, since Attributes and the child collections are live views over the tree.
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Microsoft.AspNetCore.Html;

public static class FragmentSanitizer
{
    private const string HtmlNs = "http://www.w3.org/1999/xhtml";
    private static readonly StringComparer Ord = StringComparer.Ordinal;

    // Ordinal everywhere: the default comparer runs ICU collation over names
    // the HTML spec already fixes as ASCII. Slower, and culture aware for free.
    private static readonly Dictionary<string, HashSet<string>> Allowed = new(Ord)
    {
        ["p"] = new(Ord), ["em"] = new(Ord), ["code"] = new(Ord), ["strong"] = new(Ord),
        ["a"] = new(Ord) { "href", "hreflang" },
    };
    private static readonly HashSet<string> Schemes = new(Ord) { "https", "mailto" };

    /// <summary>Returns IHtmlContent so Razor emits it raw exactly once,
    /// instead of every call site reaching for @Html.Raw.</summary>
    public static IHtmlContent Clean(string fragment)
    {
        var document = new HtmlParser().ParseDocument(fragment);
        // Snapshot with ToList: Attributes and the child lists are live views.
        foreach (var el in document.Body!.QuerySelectorAll("*").ToList())
        {
            if (!Allowed.TryGetValue(el.LocalName, out var attrs) || el.NamespaceUri != HtmlNs)
            {
                el.Remove();
                continue;
            }
            var doomed = el.Attributes
                .Where(a => !attrs.Contains(a.Name) || (a.Name == "href" && !IsSafe(a.Value)))
                .ToList();
            foreach (var attr in doomed) el.RemoveAttribute(attr.Name);
        }
        return new HtmlString(document.Body.InnerHtml);
    }

    private static bool IsSafe(string v) => Uri.TryCreate(v.Trim(), UriKind.RelativeOrAbsolute,
        out var uri) && (!uri.IsAbsoluteUri || Schemes.Contains(uri.Scheme));
}

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

System.Text.Json escapes <, >, &, ' and + by default, specifically so that serialised output is safe to embed inside a script element. The standard remedy for the resulting \u003C noise in an API response is setting JsonSerializerOptions.Encoder to JavaScriptEncoder.UnsafeRelaxedJsonEscaping, and that single line withdraws the protection from every string in the payload. Your correctly sanitized fragment then travels as a literal </script> inside a JSON island on the page, and the HTML parser, which knows nothing about JSON string quoting, ends the script element right there. The sanitizer was never wrong; the serializer downgraded it.

Performance in C#, beyond the O(n)

AngleSharp allocates a managed object per node and per attribute, so a normal fragment produces gen0 garbage that server GC reclaims cheaply; the case worth measuring is the multi-megabyte document that lives long enough to be promoted. StringComparer.Ordinal costs nothing extra here, Dictionary/HashSet already dispatch string equality through the ordinal fast path by default, but passing it explicitly avoids the comparer-object indirection of a non-default comparer and documents that culture must never leak into this lookup. A scheme check over value.AsSpan() avoids the Substring allocation entirely, and reading InnerHtml materialises a second full copy of the document where ToHtml(TextWriter, IMarkupFormatter) would stream it instead. 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 HTML Sanitizer between languages.

Real-World Applications

HTML Sanitizer is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In C# specifically, .NET, Entity Framework, and ASP.NET Core use these patterns. Understanding HTML Sanitizer helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

HTML Sanitizer 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 HTML Sanitizer 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 HTML Sanitizer 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 HTML Sanitizer?

Encoding ships in the box: System.Net.WebUtility.HtmlEncode, and System.Text.Encodings.Web.HtmlEncoder with HtmlEncoder.Create(UnicodeRanges.All) when you need finer control over which ranges survive. Parsing does not: System.Xml.XmlReader wants well-formed XML. The spec-compliant HTML5 parser is AngleSharp, whose AngleSharp.Html.Parser.HtmlParser.ParseDocument returns an IHtmlDocument of IElement nodes carrying LocalName, NamespaceUri, Attributes and RemoveAttribute; the prebuilt allowlist sanitizer Ganss.Xss.HtmlSanitizer sits on top of it. Razor's own contract is Microsoft.AspNetCore.Html.IHtmlContent.

What is the most common C# mistake when implementing HTML Sanitizer?

System.Text.Json escapes <, >, &, ' and + by default, specifically so that serialised output is safe to embed inside a script element. The standard remedy for the resulting \u003C noise in an API response is setting JsonSerializerOptions.Encoder to JavaScriptEncoder.UnsafeRelaxedJsonEscaping, and that single line withdraws the protection from every string in the payload. Your correctly sanitized fragment then travels as a literal </script> inside a JSON island on the page, and the HTML parser, which knows nothing about JSON string quoting, ends the script element right there. The sanitizer was never wrong; the serializer downgraded it.

How does HTML Sanitizer actually perform in C#?

AngleSharp allocates a managed object per node and per attribute, so a normal fragment produces gen0 garbage that server GC reclaims cheaply; the case worth measuring is the multi-megabyte document that lives long enough to be promoted. StringComparer.Ordinal costs nothing extra here, Dictionary/HashSet already dispatch string equality through the ordinal fast path by default, but passing it explicitly avoids the comparer-object indirection of a non-default comparer and documents that culture must never leak into this lookup. A scheme check over value.AsSpan() avoids the Substring allocation entirely, and reading InnerHtml materialises a second full copy of the document where ToHtml(TextWriter, IMarkupFormatter) would stream it instead. 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 Devin, 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

Want 50 audits a day? Explore SeekerPro

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.