HTML Tags in User Input
Sometimes you want to let your users input text that includes custom formatting with HTML tags. For example, the rich text input fields that we are using for our commenting engine will allow you to use the <b> or <i> tags to modify your comment.
If you include, <b>Bold Text</b> in your comment, it will be displayed as Bold Text.
The problem is that, by default, ASP.NET will reject this type of input when it automatically performs a request validation when the input is submitted. To get around this, all you have to do is turn off the request validation and create a function that will search the input and allow through the types of HTML tags that you want your users to have access to. Before writing the input to a database, make sure to HTML-encode it. This will ensure that any malicious code that may be part of the input will be handled as text and not be executed.
The Quick Solution
If you want to allow HTML code to be submitted in any form on the page, you can add a simple attribute to the Page directive. Here's the code.
<%@ Page Language="C#" ValidateRequest="false"%>
The key part to this snippet is the ValidateRequest="false". What this essentially does is tells the ASP.NET validator to stop looking for HTML/XML tags that could be potentially dangerous.
In general, this is not recommended as it opens your site up to HTML injection issues when rendering a page. A more refined approach is implementing HTMLEncoding for individual input fields.
The Best Solution
Create a function that will handle the click event of the submit button. In this function, initialize a StringBuilder object and set it equal to the HTML-encoded version of the input string. Now, go back and search the StringBuilder for the tags that you want to allow and change those back to the original HTML tag.
The following snippet shows the .aspx page code for this technique. It implements a multiline textbox that allows the user to include <b> and <i> html tags to format his input.
<html> <body></body> </html>
And now, in the .aspx code handle the button click event as follows.
Now, users can enter HTML formatted input into the multiline textbox. This quick fix can be used for any input element and is a great way to allow for formatted comments.