Knowledgebase
Validation of viewstate MAC failed
Posted by zz-James Moir on 21 June 2016 04:06 PM

Issue

You may receive following ASP.NET exception on your website:

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

Cause

If you click a postback control/link while the Page hasn't loaded completely, you might get the "Validation of ViewState MAC failed" exception. In this case be sure to check following post on ASP.NET Forums where this has been discussed in depth: http://forums.asp.net/1173230/ShowPost.aspx

Because GridView using DataKeyNames requires ViewState to be encrypted. And when ViewState is encrypted, Page adds <input type="hidden" name="_VIEWSTATEENCRYPTED" id="_VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag. But this hidden field might not bet yet rendered to the browser with long-running pages, and if you make a postback before it "gets down", browser initiates postback without this field (in form post collection)

End result is that if this field is omitted on postback, Page doesn't "know" that viewstate is encrypted and causes the prementioned Exception. E.g Page expects to be fully-loaded before you can make a postback. A similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form.

Workaround

The following workaround can be used to resolve this issue. Add the following to the applications web.config:

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