I'm looking at ways to use .NET to prevent XSS attacks and have come across the following methods to encode data:

        string asdf = WebUtility.UrlEncode(code);
        string asdf1 = HttpUtility.UrlEncode(code);
        string asdf1a = HttpUtility.UrlEncodeUnicode(code); // OBSOLETE
        string asdf1b = HttpUtility.UrlPathEncode(code);
        string asdf1c = Uri.EscapeDataString(code);
        string asdf1d = Uri.EscapeUriString(code);
        string asdf1e = HttpUtility.HtmlEncode(code);
        string asdf1f = HttpUtility.HtmlAttributeEncode(code);

(I omitted the byte[] methods... but there are more)

Given that each one of these methods work in a completely different way, and are located in completely different classes I would assume it's easy to cause an XSS issue given the wrong mix of choices.

For a given situation, when is it appropriate to use a given encoding method? Why?

  • It's worth looking at the OWASP ESAPI project, which contains a whole bunch of filtering utilities designed to help prevent XSS in output destined for HTML (inside tags, attributes, etc.), JavaScript, and CSS. Sadly the .NET version isn't quite up-to-speed yet, but it's still usable. – Polynomial Mar 4 '14 at 16:06

This is sort of the source for preventing XSS in ASP.NET (at least from Microsoft):

How To: Prevent Cross-Site Scripting in ASP.NET

Some important things to glean from the article specific to your question:

  • Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases.

  • use HttpUtility.UrlEncode to encode output URLs if they are constructed from input.

Regarding HTMLAttributeEncode:

  • The HtmlAttributeEncode method converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.

  • The string result from the HtmlAttributeEncode method should be used only for double-quoted attributes. Security issues might arise when using the HtmlAttributeEncode method with single-quoted attributes.

And finally, with UriEscapeString, use that if what you are escaping is a URI. This SO question discusses the difference between UriEscapeString and UriEscapeDataString.

Not the answer you're looking for? Browse other questions tagged or ask your own question.