Friday 5 September 2008

Disable Event Validation for an ASP.NET control

I blogged yesterday about fixing the 'Invalid postback or callback...' problem in an ASP.NET web page. The posted solution involved programatically turning off the EnableEventValidation property for the entire page. I mentioned that there are some security issues with this approach and that caution is advised when turning off security features in any code that one writes.

Well, with a bit more digging, I have now managed to turn off event validation at the control level rather than the page level. This means that you can ensure that the page is still validated, but that a specific control does not participate in event validation. From a security perspective, this is a significant improvement on the previous solution (but still not perfect).

Very briefly, the problem we are trying to solve is that ASP.NET 2.0 validates postbacks. It does this by storing the unique ID of a control (for example a drop down list) and all of it's possible values in a hash. When the client does a postback, the runtime checks that the unique ID and value combination submitted by the client exist in the hash. If the client has changed the unique id, or changed/added any values the server will not know about it and will not be able to validate the postback. This is to prevent malicious code from spoofing a postback. (see http://odetocode.com/Blogs/scott/archive/2006/03/20/3145.aspx for more info)

With things like AJAX playing about with javascript under the covers, the potential for this happening is increased.

To prevent postback validation at a control level, one must create a custom web control. Imagine that you want to turn off event validation for a drop down list, but the drop down list exposes no property/method to turn off validation.

This can be overcome by creating a custom drop down list and ommiting the [SupportsEventValidation] attribute from the class. This attribute is in fact ommited by default, so all you actually need to do is create a custom control which inherits from System.Web.Ui.WebControls.DropDownList, remove any custom implementations (by default, Visual Studio creates an override for the RenderContents method and the Text property) and you're done!

Now use this control in place of a standard drop down list and hey presto... no more errors :-)

2 comments:

Saiful Alam said...

nice blog...
visit also asp.net example

Honey said...

Wish you could give an example on creating a custom dropdown list or some link on how to create one.