Friday, July 15, 2011

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

The nanny state has definitely arrived in .NET 4.0 where all requests are not checked for possible invalid input, and in particular, HTML insertion into fields being entered into your form.  If you are lucky, you will first encounter this with a simple form and get the error message "A potentially dangerous Request.Form value was detected from the client" which at least gives you a hint at to what may be wrong.If you are unlucky, you may be using an UpdatePanel and just get the mysterious message "Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500" which gives you no hint at all.

And if you are me, you are even more unlucky because you are simply updating a TextBox text field from a ListBox selected item which simply says "<No Value>" as the value and then get the update 500 message above when you do any-however unrelated-postback to the server.

The received solution to the problem used to be to set validateRequest="false" in the page tag at the top of the page. However, in .NET 4.0 you also need to set <httpRuntime requestValidationMode="2.0" /> as well to disable the validation.
But make certain that the entry is made in the WEB.CONFIG and do not attempt to use in the Web.Debug.Config or Web.Release.Config as it will not work.  The entry must be made in the <system.web> section.

The validateRequest can also be turned off globally in the WEB.CONFIG with a section <pages validateRequest="false" />.

There is an alternative approach suggested by www.track7.org in their article disabling request validation in asp.net 4.0 by creating a class:
using System;
using System.Web.Util;

class RequestValidatorDisabled : RequestValidator
{
    protected override bool IsValidRequestString(System.Web.HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
    {
        validationFailureIndex = -1;
        return true;
    }
}
and then adding a section

<httpRuntime requestValidationType="RequestValidationDisabled" />

to the WEB.CONFIG file in the <System.Web> section which overides the standard RequestValidation and substitutes your stub. The one advantage of this is that it will allow you to add back any validation that you feel is appropriate to you web pages.

Remember that Microsoft has been nannying you and once you have disabled these checks you must then add those of your own. When a tag is displayed in a TextBox it is not a problem but if you then use the text to update a label, then you can be allowing code insertion. Use Server.HtmlEncode() to ensure that no HTML text from the user is actually displayed on your web pages unintentionally.
Be careful.

No comments:

Post a Comment