Feb 08

A few posts back, we’ve seen how we could use the AuthorizeAttribute to authorize the execution of a certain request. Today, we’ll look at another Filter which lets you validate the submitted input. Notice that we’re not talking about what I call domain validation (ie, we’re not checking if a field is null or if it has a different type of data than the one that is expected): we’re talking about input validation that ensures that a request doesn’t contain any chars that might be considered dangerous data.

If you’ve been developing web apps with ASP.NET Web Forms, then you’ll probably remember the ValidateRequest attribute of the page directive, right? That’s the kind of input validation I’m talking about here. Let’s get started…

In web forms, you’d generally enable this validation by using the previous attribute on a page (or probably by using the config file). However, that doesn’t really work here in MVC land. Why? If you think about it, it’s really simple: don’t forget that data is recovered from the current request by the controller, not by the view. So, if we want to validate the input values, we need to do it on the controller level.

To solve this problem,the team decided to add a property to the Controller class (in fact,it was added to the ControllerBase class) named ValidateRequest. When this property is set to true, the ControllerActionInvoker instance is responsible for validating the received data before invoking the requested action method.

If you want, you can also use the ValidateInputAttribute for indicating which methods should run the input validation (keep in mind that by default all the input validation will be run in all the requests). The ValidateInputAttribute is a filter attribute which implements the IAuthorizationFilter interface (which is also implemented by the AuthorizeAttribute class), so it’ll run before your action method and before other existing filters.

Using this attribute is really simple: you only need to pass a boolean which enables (or disables) input validation. Here’s an example that shows how you can disable input validation for a method:

public ActionResult About() {
//more code…

If you want, you can also apply the attribute to a controller, disabling or enabling validation for all the methods of that controller. And that’s it for today. Keep tuned for more on the MVC framework!

1 comment so far

  1. zsassasa
    9:01 am - 2-2-2010