Saturday, March 15, 2008

Validation of viewstate MAC failed

Reasons:

This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the
tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.

Resolutions:

1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:



This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.

2. Another way around the problem is to mark the form as disabled and then enable it in script once the load is complete:

function enableForm() {
document.getElementById("form").disabled = false;
}

window.onLoad = enableForm();

And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered
tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.

The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.

Thanks.
View WiZiQ Profile of Zubair Masoodi