Script injection attacks are a concern for all web
developers, whether they are using ASP.NET, ASP, or any other web development
technologies. ASP.NET includes a feature designed to automatically combat
script injection attacks, known as request validation. Request validation
checks the posted form input and raises an error if any potentially malicious
tags (such as <script>) are found. In fact, request validation disallows
any nonnumeric tags, including HTML tags (such as <b> and <img>),
and tags that do not correspond to anything (such as <xyz>).
To test the script validation features, we can create a
simple web page like the one shown below.
Figure 1

If we try to enter a block of content with a script tag and
then click the button, ASP.NET will detect the potentially dangerous value and
generate an error.
Figure 2

Disabling Request Validation
There may be such a situation where users have a genuine
need to specify HTML tags (for example, an advertisement purpose) or a block of
XML data. In these situations we need to specifically disable script validation
using the ValidateRequest Page directive, as shown below.
Listing 1
<%@ Page ValidateRequest="false" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
We can also disable request validation for an entire web
application by modifying the web.config file. We need to add or set the
validateRequest attribute of the <pages> element, as shown here.
Listing 2
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<pages validateRequest="false"/>
</system.web>
</configuration>
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write(txtInput.Text);
}
The following screenshot is showing what will happen when a
user clicks on the submit button.
Figure 2

Encode Output
Use the HttpUtility.HtmlEncode method to encode output if it
contains input from the user or from other sources such as databases.
HtmlEncode replaces characters that have special meaning in HTML-to-HTML
variables that represent those characters. For example, < is replaced with
< and " is replaced with ". Encoded data does not cause
the browser to execute code. Instead, the data is rendered as harmless HTML.
To prevent a script injection attack from happening when
request validation is turned off, we need to explicitly encode the content
before we display it using the Server object.
Listing 3
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("Entered Input is:"+Server.HtmlEncode(txtInput.Text));
}
The following screenshot is showing the output of the above mentioned
code.
Figure 3
