Why use Encoder.HtmlEncode when Sanitizer.GetSafeHtmlFragment exists

Jun 1, 2011 at 9:32 PM

Hi there,

i am using antixss v4 in an asp.net mvc 2 web app and have implemented Sanitize.GetSafeHtmlFragment() in order to accomplish server side html user input validation,  whenever ValidateInput attribute has been set to false.

My question has to do with why someone to choose Encoder.HtmlEncode() in conjunction to UnicodeCharacterEncoder.MarkAsSafe() methods, when Sanitize.GetSafeHtmlFragment() make implementation much simpler. Does it has to do with Medium - Full trust environments issue?


Jun 2, 2011 at 12:34 AM

They perform two entirely different functions

The sanitizer strips dangerous tags from HTML, so you can include it in your output and the safe tags will be left alone and become part of your output.

HTML Encode takes a string and encodes dangerous characters so you can include it in your output and any characters that would have started an HTML tag get turned into an encoded character, so they display, rather than start or finish a tag.

Jun 2, 2011 at 3:19 PM

So in my case where i just want to get protected from dangerous script injections inside my model's html inputs, the sanitizer is the perfect solution.


Jun 2, 2011 at 3:22 PM

If you are accepting HTML from the user, and wanting to output it again safely, but leaving things like <b> active then yes, then sanitizer is what you would use.

Jun 2, 2011 at 3:25 PM

Yes, this is exactly what i want. Leaving safe html tags active (like <b> you mention) and removing dangerous tags like <script>. I have already tested it and works like a charm!