solution for "Validation of viewstate MAC failed" in ASP.NET 2.0

If you are having a large page that uses lot of time to load and you are using built-in databound controls such as GridView, DetailsView or FormView which utilize DataKeyNames then there may be the cases whenever you perform a post back before the page loading is complete you get the follwoing error:

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]

It is an observation that whenever GridView uses DataKeyNames it requires the ViewState to be encrypted. For this, Page adds <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag.

Now, if the page takes lot of time to load and you click on event then this hidden field might not bet yet rendered to the browser.

It means this field was omitted during postback, and Page doesn't "know" that viewstate is encrypted and thus causes the Exception.

A solution to this problem is to add follwoing ocde in the web.config :

<pages enableEventValidation="false" viewStateEncryptionMode ="Never" />

No comments:


Powered by Blogger.