Question

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?

Was it helpful?

Solution

Try this.

var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);

OTHER TIPS

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.

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.

In an addition to the given answers: When using Razor view engine (which is the default view engine in ASP.NET), using the '@' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.

On the other hand, when you don't want the text being encoded, you have to specify that explicitly (by using @Html.Raw). Which is, in my opinion, a good thing from a security point of view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top