LA.NET [EN]

Jan 05

[Update: added the missing web.config changed required to make it work]

ASP.NET has been performing some sort of validation on user input for ages. For instance, I guess that most of us know that there is a list of chars which can’t be introduced in a textbox (ex.: <) in order to help protect our pages against vulnerabilities. Now, this validation is lazy and is performed against the data passed through the request (even though the user input validation is the most know validation, it’s also performed against query strings, cookies, etc). Until now, we could only turn this feature on and off by setting the @Page’s ValidateRequest attribute.

The good news is that from ASP.NET 4.0 onwards, this feature is *extensible*. What this means is that we can create our own “validators” for checking the input. If you want to build your own “validator”, you’ll only need to create a new class which extends the RequestValidator class. Then you can override the IsValidRequestString method and writer your own custom validation logic:

public class MyRequestValidatory : RequestValidator {
        protected override bool IsValidRequestString(
            HttpContext context, string value,
            RequestValidationSource requestValidationSource,
            string collectionKey,out int validationFailureIndex ) {
            //some code
         }
    }

As you can see,the method receives several parameters which you can use to perform your logic. As you can probably deduce from its name, the value parameter contains the string that needs to be checked. The RequestValidationSource parameter can be used to determine the kind of HTTP data that has been passed to be validated. The validationFailureIndex should only have a non-negative value when the string passed through value has forbidden chars and it should indicate the position of the string where that invalid char is used. Oh, and I almost forgot: the collectionKey parameter identifies the name of the key in the request collection that is being validated.

After building the “validator”, you need to make ASP.NET use it. The httpRuntime section exposes the requestValidationType attribute which can be used for doing that:

<httpRuntime requestValidationType=" MyRequestValidatory" />

This is another small and “sweet” update to the existing framework. And I guess that’s it for now. Stay tuned for more on ASP.NET.

2 comments so far

  1. OmariO
    12:28 am - 1-6-2010

    They even let override encoding and decoding of html

  2. Jef claes
    7:06 am - 1-6-2010

    I”ve been reading about ASP.NET 4 from the beginning. This is totally new for me. Thanks for this post!