HTML Sanitizer 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 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
HTML Sanitizer in C#: what you actually reach for
C# implementation
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 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 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).
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 Devin, 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.