5

Can anyone please let me know the difference between these two? AntiXss.HtmlEncode() vs AntiXss.GetSafeHtmlFragment()

Shoban
  • 22,920
  • 8
  • 63
  • 107
Biki
  • 2,518
  • 8
  • 39
  • 53

3 Answers3

9

HtmlEcode actually encodes tags:

AntiXss.HtmlEncode("<b>hello</b><script>");
//Output: &lt;b&gt;hello&lt;/b&gt;&lt;script&gt;

GetSafeHtmlFragment (AntiXss v4.0) returns HTML fragments with tags intact:

Sanitizer.GetSafeHtmlFragment("<b>hello2</b><script>")
//Output: <b>hello2</b>

Update

Many consider the latest version of Microsoft's AntiXSS library broken. I've started using HTML Sanitizer as a decent replacement.

Brian Chavez
  • 8,048
  • 5
  • 54
  • 47
  • 2
    well, GetSafeHtmlFragment doesn't really returns the HTML fragments intact, it does 2 things: - properly form malformed html - remove html tags not on whitelist – murki Mar 30 '11 at 00:47
  • Unfortunately, `AntiXSS.GetSafeHtmlFragment()` turned to be vulnerable in older versions and useless in newer version (it now strips almost all HTML tags possible and became unusable) - [more details here](http://stackoverflow.com/questions/18103360/getsafehtmlfragment-removing-all-html-tags) – BornToCode Jan 19 '15 at 17:12
  • 1
    A note for future readers: the `AntiXss` namespace has been deprecated. Use `Encoder` instead. Ex: `Encoder.HtmlEncode("example");` – Brian Kraemer Aug 10 '15 at 14:21
7

It should also be mentioned that antixss.GetSafeHtmlFragment does encode characters too. A double quote changes to &quot;. A plus sign turns into &#43; etc.

Spudley
  • 166,037
  • 39
  • 233
  • 307
Joel
  • 71
  • 1
  • 2
  • Any clue on why that would be the case? – Sam7 Aug 18 '15 at 02:02
  • That's pathetic... Why would I use an anti xss library if it encodes the characters anyways? Scripts can't work if I would encode them for sure. I wonder what I miss.. Encoding is not an option for most of us – yakya Jan 26 '18 at 13:18
5

I would also add that GetSafeHtmlFragment messes up your CSS, by ading x_ in front of styles, and removes your HTML entity encoding. It is a less than beautiful thing.

Herc

CoolBeans
  • 20,654
  • 10
  • 86
  • 101
Herc
  • 51
  • 1
  • 1
  • (AntiXss v4.2.0) "The HTML Sanitizer now removes all CSS from the section of an HTML page. If a – Timbob Jan 12 '12 at 15:51