HtmlSanitizer 10.0.1120

dotnet add package HtmlSanitizer --version 10.0.1120
                    
NuGet\Install-Package HtmlSanitizer -Version 10.0.1120
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HtmlSanitizer" Version="10.0.1120" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HtmlSanitizer" Version="10.0.1120" />
                    
Directory.Packages.props
<PackageReference Include="HtmlSanitizer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add HtmlSanitizer --version 10.0.1120
                    
#r "nuget: HtmlSanitizer, 10.0.1120"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package HtmlSanitizer@10.0.1120
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=HtmlSanitizer&version=10.0.1120
                    
Install as a Cake Addin
#tool nuget:?package=HtmlSanitizer&version=10.0.1120
                    
Install as a Cake Tool

HtmlSanitizer

NuGet version Build status codecov.io Sonarcloud Quality Gate

netstandard2.0 net46 net8.0

HtmlSanitizer is a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks. It uses AngleSharp to parse, manipulate, and render HTML and CSS.

Because HtmlSanitizer is based on a robust HTML parser it can also shield you from deliberate or accidental "tag poisoning" where invalid HTML in one fragment can corrupt the whole document leading to broken layout or style.

In order to facilitate different use cases, HtmlSanitizer can be customized at several levels:

  • Configure allowed HTML tags through the property AllowedTags. All other tags will be stripped.
  • Configure allowed HTML attributes through the property AllowedAttributes. All other attributes will be stripped.
  • Configure allowed CSS property names through the property AllowedCssProperties. All other styles will be stripped.
  • Configure allowed CSS at-rules through the property AllowedAtRules. All other at-rules will be stripped.
  • Configure allowed URI schemes through the property AllowedSchemes. All other URIs will be stripped.
  • Configure HTML attributes that contain URIs (such as "src", "href" etc.) through the property UriAttributes.
  • Configure HTML attributes that contain a list of URIs (such as "srcset", "ping") through the property UriListAttributes. Every entry is checked separately.
  • Provide a base URI that will be used to resolve relative URIs against.
  • Sanitize a fragment for the element it will be inserted into, rather than for <body>, through SanitizeFragment(). This keeps markup such as a lone <th> that is only valid deeper in the tree.
  • Cancelable events are raised before a tag, attribute, or style is removed.
  • All of the above can be set in one go by passing an HtmlSanitizerOptions object to the constructor. new HtmlSanitizerOptions() starts pre-populated with the same defaults as new HtmlSanitizer(), so you only need to set what you want to change; use HtmlSanitizerOptions.Empty() instead if you want a blank slate, see Configuring with HtmlSanitizerOptions.

Usage

Install the HtmlSanitizer NuGet package. Then:

using Ganss.Xss;
var sanitizer = new HtmlSanitizer();
var html = @"<script>alert('xss')</script><div onload=""alert('xss')"""
    + @"style=""background-color: rgba(0, 0, 0, 1)"">Test<img src=""test.png"""
    + @"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
var sanitized = sanitizer.Sanitize(html, "https://www.example.com");
var expected = @"<div style=""background-color: rgba(0, 0, 0, 1)"">"
    + @"Test<img src=""https://www.example.com/test.png"" style=""margin: 10px""></div>";
Assert.Equal(expected, sanitized);

There's an online demo, plus there's also a .NET Fiddle you can play with.

More example code and a description of possible options can be found in the Wiki.

Configuring with HtmlSanitizerOptions

A sanitizer can also be configured in one go by passing an HtmlSanitizerOptions object to the constructor. Every collection on HtmlSanitizerOptions starts out pre-populated from HtmlSanitizerDefaults, the same defaults new HtmlSanitizer() uses, so you only need to set what you want to change:

var options = new HtmlSanitizerOptions();
options.AllowedTags.Clear();
options.AllowedTags.Add("a");
options.AllowedTags.Add("img");
// AllowedAttributes, UriAttributes, AllowedSchemes, etc. remain at their defaults
var sanitizer = new HtmlSanitizer(options);

Reassigning a collection outright, rather than mutating the pre-populated one, still replaces the default for that property alone - the other properties are unaffected:

var sanitizer = new HtmlSanitizer(new HtmlSanitizerOptions
{
    AllowedTags = new HashSet<string> { "a", "img" },
    AllowedAttributes = new HashSet<string> { "href", "src" },
    // UriAttributes and AllowedSchemes are not reassigned here, so they keep their defaults
});

If you want a blank slate instead - nothing allowed until you add it - start from HtmlSanitizerOptions.Empty():

var options = HtmlSanitizerOptions.Empty();
options.AllowedTags.Add("a");
options.AllowedAttributes.Add("href");
var sanitizer = new HtmlSanitizer(options);
// UriAttributes is empty, so href is *not* screened against AllowedSchemes
// <a href="javascript:alert(1)">click</a> is preserved as-is

UriAttributes is a screening list rather than an allow list: an attribute not in it is not treated as carrying a URI at all, so its value is never checked against AllowedSchemes. This matters most when building an allowlist from Empty(), where it's easy to allow href without also adding it to UriAttributes. And UriAttributes and AllowedSchemes need to be set together - screening an attribute against an empty scheme set drops every absolute URI, valid https ones included:

var options = HtmlSanitizerOptions.Empty();
options.AllowedTags.Add("a");
options.AllowedAttributes.Add("href");
options.UriAttributes.Add("href");
// AllowedSchemes left empty - every absolute URI is dropped
var sanitizer = new HtmlSanitizer(options);
// <a href="https://example.com">ok</a> becomes <a>ok</a>

Tags allowed by default

a, abbr, acronym, address, area, article, aside, b, bdi, big, blockquote, body, br, button, caption, center, cite, code, col, colgroup, data, datalist, dd, del, details, dfn, dir, div, dl, dt, em, fieldset, figcaption, figure, font, footer, form, h1, h2, h3, h4, h5, h6, head, header, hr, html, i, img, input, ins, kbd, keygen, label, legend, li, main, map, mark, menu, menuitem, meter, nav, ol, optgroup, option, output, p, pre, progress, q, rp, rt, ruby, s, samp, section, select, small, span, strike, strong, sub, summary, sup, table, tbody, td, textarea, tfoot, th, thead, time, tr, tt, u, ul, var, wbr

Attributes allowed by default

abbr, accept-charset, accept, accesskey, action, align, alt, autocomplete, autosave, axis, bgcolor, border, cellpadding, cellspacing, challenge, char, charoff, charset, checked, cite, clear, color, cols, colspan, compact, contenteditable, coords, datetime, dir, disabled, draggable, dropzone, enctype, for, frame, headers, height, high, href, hreflang, hspace, ismap, keytype, label, lang, list, longdesc, low, max, maxlength, media, method, min, multiple, name, nohref, noshade, novalidate, nowrap, open, optimum, pattern, placeholder, prompt, pubdate, radiogroup, readonly, rel, required, rev, reversed, rows, rowspan, rules, scope, selected, shape, size, span, spellcheck, src, start, step, style, summary, tabindex, target, title, type, usemap, valign, value, vspace, width, wrap

Note: to prevent classjacking and interference with classes where the sanitized fragment is to be integrated, the class attribute is disallowed by default. It can be added as follows:

var sanitizer = new HtmlSanitizer();
sanitizer.AllowedAttributes.Add("class");
var sanitized = sanitizer.Sanitize(html);

CSS properties allowed by default

align-content, align-items, align-self, all, animation, animation-delay, animation-direction, animation-duration, animation-fill-mode, animation-iteration-count, animation-name, animation-play-state, animation-timing-function, backface-visibility, background, background-attachment, background-blend-mode, background-clip, background-color, background-image, background-origin, background-position, background-position-x, background-position-y, background-repeat, background-repeat-x, background-repeat-y, background-size, border, border-bottom, border-bottom-color, border-bottom-left-radius, border-bottom-right-radius, border-bottom-style, border-bottom-width, border-collapse, border-color, border-image, border-image-outset, border-image-repeat, border-image-slice, border-image-source, border-image-width, border-left, border-left-color, border-left-style, border-left-width, border-radius, border-right, border-right-color, border-right-style, border-right-width, border-spacing, border-style, border-top, border-top-color, border-top-left-radius, border-top-right-radius, border-top-style, border-top-width, border-width, bottom, box-decoration-break, box-shadow, box-sizing, break-after, break-before, break-inside, caption-side, caret-color, clear, clip, color, column-count, column-fill, column-gap, column-rule, column-rule-color, column-rule-style, column-rule-width, column-span, column-width, columns, content, counter-increment, counter-reset, cursor, direction, display, empty-cells, filter, flex, flex-basis, flex-direction, flex-flow, flex-grow, flex-shrink, flex-wrap, float, font, font-family, font-feature-settings, font-kerning, font-language-override, font-size, font-size-adjust, font-stretch, font-style, font-synthesis, font-variant, font-variant-alternates, font-variant-caps, font-variant-east-asian, font-variant-ligatures, font-variant-numeric, font-variant-position, font-weight, gap, grid, grid-area, grid-auto-columns, grid-auto-flow, grid-auto-rows, grid-column, grid-column-end, grid-column-gap, grid-column-start, grid-gap, grid-row, grid-row-end, grid-row-gap, grid-row-start, grid-template, grid-template-areas, grid-template-columns, grid-template-rows, hanging-punctuation, height, hyphens, image-rendering, isolation, justify-content, left, letter-spacing, line-break, line-height, list-style, list-style-image, list-style-position, list-style-type, margin, margin-bottom, margin-left, margin-right, margin-top, mask, mask-clip, mask-composite, mask-image, mask-mode, mask-origin, mask-position, mask-repeat, mask-size, mask-type, max-height, max-width, min-height, min-width, mix-blend-mode, object-fit, object-position, opacity, order, orphans, outline, outline-color, outline-offset, outline-style, outline-width, overflow, overflow-wrap, overflow-x, overflow-y, padding, padding-bottom, padding-left, padding-right, padding-top, page-break-after, page-break-before, page-break-inside, perspective, perspective-origin, pointer-events, position, quotes, resize, right, row-gap, scroll-behavior, tab-size, table-layout, text-align, text-align-last, text-combine-upright, text-decoration, text-decoration-color, text-decoration-line, text-decoration-skip, text-decoration-style, text-indent, text-justify, text-orientation, text-overflow, text-shadow, text-transform, text-underline-position, top, transform, transform-origin, transform-style, transition, transition-delay, transition-duration, transition-property, transition-timing-function, unicode-bidi, unicode-range, user-select, vertical-align, visibility, white-space, widows, width, word-break, word-spacing, word-wrap, writing-mode, z-index

CSS at-rules allowed by default

namespace, style

style refers to style declarations within other at-rules such as @media. Disallowing @namespace while allowing other types of at-rules can lead to errors. Property declarations in @font-face and @viewport are not sanitized.

Note: the style tag is disallowed by default.

URI schemes allowed by default

http, https

Note: Protocol-relative URLs (e.g. <a href="//github.com">//github.com</a>) are allowed by default (as are other relative URLs).

to allow mailto: links:

sanitizer.AllowedSchemes.Add("mailto");

Default attributes that contain URIs

action, background, cite, codebase, data, dynsrc, formaction, href, icon, longdesc, lowsrc, manifest, poster, src, xlink:href

The value of an attribute listed in UriAttributes is checked against AllowedSchemes. An attribute that carries a URI but is not listed keeps its value as-is, so if you add such an attribute to AllowedAttributes you should add it to UriAttributes as well:

sanitizer.AllowedAttributes.Add("data-thumbnail");
sanitizer.UriAttributes.Add("data-thumbnail");

The same applies to the attributes listed above when you configure the sanitizer through HtmlSanitizerOptions, whose UriAttributes starts out empty - see Configuring with HtmlSanitizerOptions.

Note: attributes that merely name something in the same document rather than locating a resource - usemap, classid, profile - are deliberately not treated as URI attributes. Nothing fetches them, and resolving them against a base URI would break them: usemap="#map" has to stay a hash-name reference to match its <map>.

Default attributes that contain lists of URIs

archive, ping, srcset

These hold several URIs in one value, so each entry is checked on its own and the failing ones are dropped; the attribute itself is removed only if nothing survives. srcset is parsed as a candidate list so that descriptors are kept with the URI they belong to, and commas inside a URI do not split it.

// srcset="https://example.com/a.jpg 1x, javascript:alert(1) 2x"
// becomes srcset="https://example.com/a.jpg 1x"

Checking such an attribute through UriAttributes instead would inspect the whole value as a single URI, which only ever looks at the first entry - so use UriListAttributes for these.

The srcdoc attribute

srcdoc holds a complete HTML document rather than a URI, and a browser parses and runs it in its own browsing context. It is therefore not a URI attribute: if you allow it, its content is sanitized as HTML with the same settings as the surrounding document.

sanitizer.AllowedTags.Add("iframe");
sanitizer.AllowedAttributes.Add("srcdoc");
// <iframe srcdoc="&lt;img src=x onerror=alert(1)&gt;"></iframe>
// becomes <iframe srcdoc="&lt;img src=&quot;x&quot;&gt;"></iframe>

Nested srcdoc documents are sanitized as well, up to a fixed depth, beyond which the attribute is removed.

Sanitizing a fragment in context

Sanitize() parses its input as if it were being inserted into <body>. Markup that is only valid deeper in the tree is therefore discarded by the parser before sanitization ever sees it, exactly as it would be by div.innerHTML in a browser:

sanitizer.Sanitize(@"<th>Header</th>"); // "Header" - the th is gone

Use SanitizeFragment() to name the element the fragment will be inserted into:

sanitizer.SanitizeFragment(@"<th>Header</th>", "tr"); // "<th>Header</th>"

This is useful when you sanitize table rows, list items, or <option> elements on their own, e.g. to return them from an endpoint that patches part of a page.

The result is only safe in the context it was sanitized for, so insert it into that same context. A fragment sanitized for tr that is put into a <div> instead gets re-parsed under different rules, and the tree the browser ends up with is not the one that was screened.

Contexts whose content is raw text - style, script, xmp, iframe, noembed and noframes - are rejected with an ArgumentException. The parser turns a fragment in those into a single text node, so there are no tags or attributes left to remove and nothing is escaped on the way out; the input would come back verbatim, looking sanitized without having been. An unknown context name is rejected too, so a typo fails instead of quietly falling back to <body> behaviour.

There is also an overload taking an IElement, for callers that hold one already:

using var document = sanitizer.HtmlParserFactory().ParseDocument(string.Empty);
var context = document.CreateElement("tr");
sanitizer.SanitizeFragment(@"<th>Header</th>", context); // "<th>Header</th>"

Only the local name of the element is read - the parser rebuilds the context in the HTML namespace, so an element carries no more information into the parse than a tag name does. The element itself is left untouched, so you can reuse one across calls.

For the same reason a context outside the HTML namespace is rejected with an ArgumentException rather than parsed as if it were an HTML element of the same name. An SVG or MathML element does not put the parser into foreign content here the way it does inside a document, and a fragment screened under HTML rules but inserted under SVG or MathML ones is not the tree that was screened. Sanitize such markup together with the element that establishes the foreign context - an <svg> element and its content in one string - using Sanitize().

PostProcessDom handlers see the document the fragment was parsed into, not the kind of document Sanitize() gives them: the fragment hangs off a stand-in for the context, detached from the document tree, so the document has no Body and the fragment's nodes are not below it. Use PostProcessNode, which is raised for each node of the fragment as usual.

Thread safety

The Sanitize(), SanitizeFragment() and SanitizeDocument() methods are thread-safe, i.e. you can use these methods on a single shared instance from different threads provided you do not simultaneously set instance or static properties. A typical use case is that you prepare an HtmlSanitizer instance once (i.e. set desired properties such as AllowedTags etc.) from a single thread, then call Sanitize()/SanitizeFragment()/SanitizeDocument() from multiple threads.

Text content not necessarily preserved as-is

Please note that as the input is parsed by AngleSharp's HTML parser and then rendered back out, you cannot expect the text content to be preserved exactly as it was input, even if no elements or attributes were removed. Examples:

  • 4 < 5 becomes 4 &lt; 5
  • <SPAN>test</p> becomes <span>test<p></p></span>
  • <span title='test'>test</span> becomes <span title="test">test</span>

On the other hand, although some broken HTML is fixed by the parser, the output might still contain invalid HTML. Examples:

  • <div><li>test</li></div>
  • <ul><br><li>test</li></ul>
  • <h3><p>test</p></h3>

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 is compatible.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (288)

Showing the top 5 NuGet packages that depend on HtmlSanitizer:

Package Downloads
OrchardCore.Infrastructure

Orchard Core CMS is a Web Content Management System (CMS) built on top of the Orchard Core Framework. Implementation for OrchardCoreCMS Infrastructure

Kentico.Xperience.AspNetCore.WebApp

Contains assemblies and content items required to integrate Kentico Xperience into ASP.NET Core applications.

VirtoCommerce.CatalogModule.Data

Package Description

Soneta.Business

Składnik programu Soneta. Program obsługi firmy: kadry-płace, księgowość, handel, magazyn, CRM, BI ...

Abp.HtmlSanitizer

Abp.HtmlSanitizer

GitHub repositories (40)

Showing the top 20 popular GitHub repositories that depend on HtmlSanitizer:

Repository Stars
abpframework/abp
Open-source web application framework for ASP.NET Core! Offers an opinionated architecture to build enterprise software solutions with best practices on top of the .NET. Provides the fundamental infrastructure, cross-cutting-concern implementations, startup templates, application modules, UI themes, tooling and documentation.
aspnetboilerplate/aspnetboilerplate
ASP.NET Boilerplate - Web Application Framework
dodyg/practical-aspnetcore
Practical samples of ASP.NET Core 11, 10, 9, 8.0, 7.0, 6.0, 5.0, 3.1, 2.2, and 2.1,projects you can use. Readme contains explanations on all projects.
OrchardCMS/OrchardCore
Orchard Core is an open-source modular and multi-tenant application framework built with ASP.NET Core, and a content management system (CMS) built on top of that framework.
btcpayserver/btcpayserver
Accept Bitcoin payments. Free, open-source & self-hosted, Bitcoin payment processor.
ErsatzTV/legacy
Open-source platform that transforms your personal media library into live, custom TV channels.
SeriaWei/ZKEACMS
ZKEACMS build with .Net 8 (.Net CMS)可视化设计在线编辑内容管理系统
smartstore/SmartStoreNET
Open Source ASP.NET MVC Enterprise eCommerce Shopping Cart Solution
openbullet/OpenBullet2
OpenBullet reinvented
HawaiiBeach/TinyNvidiaUpdateChecker
The best NVIDIA GPU update checker for Windows power users/gamers. Fully open sourced and lightweight.
smartstore/Smartstore
A modular, scalable and ultra-fast open-source all-in-one eCommerce platform built on ASP.NET Core 10
NuGet/NuGetGallery
NuGet Gallery is a package repository that powers https://www.nuget.org. Use this repo for reporting NuGet.org issues.
ariacom/Seal-Report
Database Reporting Tool and Tasks (.Net)
bitfoundation/bitplatform
Build all of your apps using what you already know and love ❤️
dnnsoftware/Dnn.Platform
DNN (formerly DotNetNuke) is the leading open source web content management platform (CMS) in the Microsoft ecosystem.
cofoundry-cms/cofoundry
Cofoundry is an extensible and flexible .NET Core CMS & application framework focusing on code first development
lysilver/KopSoftWms
KopSoft仓库管理系统
blazorblueprintui/ui
A collection of accessible, headless primitives and beautifully-designed components for Blazor inspired by shadcn/ui.
replaysMike/Binner
Open source parts inventory system for makers, electronics hobby, and professional engineers
VocaDB/vocadb
VocaDB is a Vocaloid Database with translated artists, albums, music videos and more.
Version Downloads Last Updated
10.0.1120 17,119 11/2/2026
10.0.1102-beta 1,392 10/21/2026
10.0.1075-beta 4,052 10/1/2026
10.0.1037-beta 6,701 8/27/2026
10.0.2 231 11/2/2026
9.2.1039 4,924,012 8/28/2026
9.2.995 1,990,916 8/10/2026
9.1.982 1,149,999 8/3/2026
9.1.981 8,805 8/3/2026
9.1.974 634,039 7/30/2026
9.1.973 1,163,680 7/27/2026
9.1.968-beta 213,928 7/21/2026
9.1.966-beta 262,368 7/20/2026
9.1.949-beta 599,955 6/19/2026
9.1.923-beta 96,304 4/27/2026
9.1.893-beta 926,890 2/2/2026
9.1.891-beta 75,275 11/24/2025 9.1.891-beta has at least one vulnerability with moderate severity.
9.0.967 348,601 7/21/2026
9.0.892 21,304,257 2/2/2026
9.0.889 2,298,324 11/24/2025 9.0.889 has at least one vulnerability with moderate severity.
Loading failed