Friday, January 9, 2015

ASP.NET potentially dangerous Request.Form value was detected

A few days ago, while working on an ASP.NET 4.0 project, I got an error. The error was, when user enters non-encoded HTML content into text box then she/he got something like the following error message:



This was because .NET detected something in the entered text which looked like an HTML statement. Then I got a solution that is 'Request Validation', that is a feature in ASP.Net application to protest cross site scripting attack.

To disable request validation, I added the following to the existing "page" directive in .aspx file.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false"%>

But I still got the same error message. Later on I found that, for .NET 4, we need to add requestValidationMode="2.0" to the httpRuntime configuration section of the web.config file as following:

<system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime requestValidationMode="2.0"/>
</system.web>

If you wants to turn off request validation globally, the following line in the web.config file within <system.web> section will help:

<pages validateRequest="false" />

Note: Avoid the last example because there is a security issue. The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting attacks.