tags:

views:

1016

answers:

5

PHP has a great function called htmlspecialcharacters() where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's almost a one stop shop for sanitizing input. Very nice right?

Well is there an equivalent in any of the .NET libraries?

If not, can anyone link to any code samples or libraries that do this well?

+4  A: 

System.Web.HttpUtility.HtmlEncode(string)

Forgotten Semicolon
+5  A: 

Try this.

var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);
Nick Berardi
+3  A: 

Don't know if there's an exact replacement, but there is a method HtmlUtility.HtmlEncode that replaces special characters with their HTML equivalents. A close cousin is HtmlUtility.UrlEncode for rendering URL's. You could also use validator controls like RegularExpressionValidator, RangeValidator, and System.Text.RegularExpression.Regex to make sure you're getting what you want.

Jason Shoulders
A: 

Actually, you might want to try this method:

HttpUtility.HtmlAttributeEncode()

Why? Citing the HtmlAttributeEncode page at MSDN docs:

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

michalstanko
A: 

None of these methods support the $double_encode flag from the PHP function.

Anyone know of a .NET function that does something equivalent to $double_encode=false?

mindplay.dk