-
Notifications
You must be signed in to change notification settings - Fork 199
Getting Started
The simplest method of getting started is to add the NuGet package to your project:
Install-Package HtmlSanitizer
If you cannot use NuGet directly in your project, you can also clone and build the source, and then add a reference to the HtmlSanitizer assembly.
Once you have a reference to the HtmlSanitizer assembly, using the library is fairly straightfoward.
To begin, create an instance of HtmlSanitizer:
var sanitizer = new HtmlSanitizer();
Next, let's create an example of "bad" input. Here's an example of unsanitized text containing an XSS attack:
var html = @"<script>alert('xss')</script><div onload=""alert('xss')"""
+ @"style=""background-color: test"">Test<img src=""test.gif"""
+ @"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
Call the Sanitize
method to clean the text above. In this example, we're adding a base URL as an argument, which will be used to resolve any relative links in the content:
var sanitized = sanitizer.Sanitize(html, "http://www.example.com");
This last bit is just a test to prove the text was cleaned properly. In real life, you would store, display, etc. the text as your requirements dictate:
Assert.That(sanitized, Is.EqualTo(@"<div style=""background-color: test"">"
+ @"Test<img style=""margin: 10px"" src=""http://www.example.com/test.gif""></div>"));
The Sanitize
method has only one required parameter, html
, which contains the markup to be sanitized. You may also supply a base URL (used for resolving relative links) and an IMarkupFormatter
object for formatting the sanitized markup.
There's an online demo, and a .NET Fiddle you can experiment with.