If ASP.NET code that generates HTML using some input, we need to evaluate appropriate action for application.
Encoding output methods:
- Encode HTML output.
- Encode URL output.
- Filter user input.
Encode HTML Output:
If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the HttpUtility.HtmlEncode method as shown in the following code example.
Do this if the text came from user input, a database, or a local file.
Response.Write(HttpUtility.HtmlEncode(Request.Form["stringvalue"]));
Encode URL Output:
If you return URL strings that contain input to the client, use the HttpUtility.
UrlEncode method to encode these URL strings as shown in the following code example.
Response.Write(HttpUtility.UrlEncode(urlString));
Filter User Input:
If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page.
If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept.
A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).
To safely allow restricted HTML input Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
Encode the string input with the HtmlEncode method.
Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.
e.g.
<%@ Page Language="C#" ValidateRequest="false"%>
StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(htmlInputTxt.Text));
sb.Replace("<b>", "<b>");
sb.Replace("</b>", "");
sb.Replace("<i>", "<i>");
Response.Write(sb.ToString());
New <%: %> Code Nugget Syntax:
With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so. This eliminates the need to explicitly HTML encode content like we did in the example above. Instead, you can just write the more concise code below to accomplish the exact same thing:
e.g.
<div>
<%: Model.Content %>
</div>
Happy Coding !!