sententia
Home    Blog

A potentially dangerous Request.Form value was detected

With my latest upgrade of the CMS to version 3.4, upon hitting logout I got an error:  System.Web.HttpRequestValidationException  A potentially dangerous Request.Form value was detected from the client
 
I updated web.config per link info below
<configuration>
<system.web>
<pages
validateRequest="false"
/>
<httpRuntime
requestValidationMode="2.0"/>
</system.web>
</configuration>
 
 
 
Excerpt from link above

This is a common error that ASP.NET developers have run into many times. We will see in this article a few ways on how to avoid it, both in Web Forms and MVC.

This error occurs mostly because the data that are sent in the web server contain HTML. By default there a validation check on all input so that our web application has a basic protection from XSS attacks.
The easy way is to disable this validation process. This can be done by setting the below properties in the Web.config file.

<configuration>
<system.web>
<pages
validateRequest="false"
/>
</system.web>
</configuration>

In .NET 4.0, you need to change one more property.

<configuration>
<system.web>
<pages
validateRequest="false"
/>
<httpRuntime
requestValidationMode="2.0"/>
</system.web>
</configuration>

If you want to apply this setting to a specific page, you can set it in the page directive of your .aspx file.

<%@ Page Language="vb"
AutoEventWireup="false"
CodeBehind="Example.aspx.cs"

Inherits="Example.Example"
ValidateRequest="false" %>

In case your web application is an ASP.NET MVC project and want to disable page validation for a specific view, you can set this property to its controller.

[Post, ValidateInput(false)]public ActionResult Edit(...)
{
...}

In MVC, you can actually declare which properties of your model you want to exclude from the validation process.

[HttpPost, ValidateInput(true, Exclude =
"YourFieldName")]public
virtual ActionResult Edit(...){
...}

Another approach is to set at the property of the Model to allow HTML content.

[AllowHtml]public
string Description {
get;
set;
}

Going back to Web Forms, if you want to allow HTML / JavaScript for a specific field, there is no direct way to do it. A nice trick you could do, is to encode the HTML in the client side and then decode it in the server side.
The client side code

 
// The event to escape the data and store in our HiddenFieldjQuery('.allow_html textarea').blur(function
()
{    jQuery(jQuery(this).parent()).find('input[type="hidden"]').val(escape(jQuery(this).val()));}); // The code to unescape the code and set it in our textboxjQuery('.allow_html textarea').each(function(idx, item)
{
var value = jQuery(jQuery(item).parent()).find('input[type="hidden"]').val();    jQuery(item).val(unescape(value));});

The server side code

// encode the dataHtmlCodeHiddenField.Value
= Uri.EscapeDataString(EscapedHtml);// decode the datastring myHtml = Uri.UnescapeDataString(HtmlCodeHiddenField.Value);