By David E.
On rare occasions inside our web application it is necessary to allow the user to enter some content in html format. In previous versions this was possible, and it was the responsibility of the programmer to validate those labels to prevent a user from entering malicious code to our application.
With ASP.net 4.0 the information will now be validated automatically. If a user tries to add html tags to a web application, the result will be an exception. This validation feature can be disabled with a simple statement of the web.config file.
The first thing to do in Visual Studio 2010 is to create a new web application, then we can add a new web form and then create the basic controls that capture html tags and a button that causes a postback from the site.
<asp:TextBox ID="txtComments" runat="server" Rows="4" TextMode="MultiLine" ClientIDMode="Static" Width="400px">asp:TextBox>
<asp:Button ID="btnInsertScript" runat="server" Text="Insert Inline"
onclick="btnInsertScript_Click" />
On the CodeBehind of our page we can see that the html is actually captured and properly painted.
htmlCode = HttpUtility.HtmlEncode(txtComments.Text);
Response.Write(this.txtComments.Text);
When running the application and capturing the HTML within that textbox (and because even change the validation mode in the web config) we get the following exception.
It is important to note that this exception occurs inside the HttpRequest, ie., even if our code is prepared to handle exceptions with a try catch, this error occurs before executing any code of our site, including the Load. If you want to handle this exception in a custom way, you need to do it inside the Global.asax.cs file with the Application_Error method.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Response.Redirect("ErrorPage.htm");
}
This method of exception handling will control any exception that is not properly handled in the application.
If we want this automatic validation to be disabled to allow html input in our textbox, you need to add the following tag within
<httpRuntime requestValidationMode="2.0" />
This will disable the validation and allow the capture of html:
Important note: This is a way to allow the user to enter html tags inside our application. However, you should never rely on any text captured by a user, it may contain malicious code that could cause failures in our application. It is best that when you are returning a captured text to the user interface, always use the HtmlEncode method:
HttpUtility.HtmlEncode(txtComments.Text);
In this way all html tags will be fully rendered on the screen and not interpreted by the browser. If you want to display the html that the user enters, it is best to use specific controls for this edition, or adequately control the code in which the HTML will be injected.
No comments:
Post a Comment