A potentially dangerous Request.Form value was detected from the client …

written by Jaider Ariza on July 17, 2012 in Security with no comments

If you see this exception in your page:

It’s because you have unhandled code that is vulnerable to script attacks creating a very high risk-prone in your system.

By default ASP.Net does the validation for you and return an error page with the form control (a text entry control) with the piece of data with the risk-prone.

Here an example of this problem:

ASPX Page:

C# Code behind:

In this case there are two alternatives:

Case 1: Work with ASP .Net Validation Request

First of all you have to catch the exception: HttpRequestValidationException. In order to achieve this, you have to override the method OnError on the page and check if it is the exception.

  • Show Friendly Message:

  • Redirect to an Error Page:

Or you can transfer or redirect to himself, but it will clear out the form.

On Load:

Whether you decided to redirect to an error page or itself, remember that the user can go back and continue filling the form. Therefore, it’s important to specify the error details.

Considerations:

You could try to use GET-FORM and send the form values by Url, in this case you’ll encode the QueryString parameters OnError and decode them OnLoad/OnRender (no tested yet).

Case 2: Validate Request by Yourself

In this case, you’ll start by disabling ASP .Net Validation Request. It’s just two simple steps.

First, disable Validation Request in the page:

NOTE: In MVC, you should use the ValidateInput(false) attribute on the controller method.

Second, set the requestValidationMode to 2.0 in the configuration file:

  • Client Validation

ASPX Page:

  • Server Validation

C# Code behind:

Considerations:

I recommend to use both Client + Server Validations.

References:

How To: Protect From Injection Attacks in ASP.NET http://msdn.microsoft.com/en-us/library/ff647397.aspx

Regular Expressions http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

How to handle HttpRequestValidationException http://forums.asp.net/t/811547.aspx/1?How+to+handle+HttpRequestValidationException

Potentially dangerous Request.Form value was detected from the client http://www.dreamincode.net/forums/topic/234664-potentially-dangerous-requestform-value-was-detected-from-the-client/