Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Validation of ViewState MAC failed

Tags:

asp.net-mvc

After publishing a new build of my ASP.NET MVC web application, I often see this exception thrown when browsing to the site:

System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not supplied or was invalid. ---> System.Web.HttpException: 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. ---> System.Web.UI.ViewStateException: Invalid viewstate.

This exception will continue to occur on each page I visit in my web application until I close out of Firefox. After reopening Firefox, the site works perfectly. Any idea what's going on?

Additional notes:

  1. I am not using any ASP.NET web controls (there are no instances of runat="server" in my application)
  2. If I take out the <%= Html.AntiForgeryToken %> from my pages, this problem seems to go away
like image 844
Kevin Pang Avatar asked Sep 01 '09 00:09

Kevin Pang


People also ask

How do I fix validation ViewState failed MAC?

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.

What is ViewState MAC in asp net?

The ViewState is a parameter specific to the ASP.NET framework, it's used as a breadcrumb trail when the user navigates the application preserving values and controls between different web pages. Present on the pages in the __viewstate parameter, all the values are serialized and encoded in base64 in a hidden field.

What causes invalid ViewState?

The main reason for "Invalid Viewstate" error is the exception is thrown when the ViewState has become "large" and the user clicks a button before a previous request has completed...


1 Answers

Under the covers, the MVC AntiForgeryToken attribute uses the machinekey for encryption. If you don't specify a machinekey in the web.config (see here), one is automatically generated for you by ASP.NET (full description).

If the ASP.NET application is restarted (e.g. do an iisreset), the AntiForgeryToken within the browser cookie will still be encrypted with an old machine key, hence why it crashes with the above error.

So you should always specify a machinekey in your web.config when using MVC, e.g.

<configuration>
    <system.web>
        <machineKey  
            validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
            decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
            validation="SHA1"
            decryption="AES"
        />
    ...
like image 108
Dunc Avatar answered Sep 28 '22 06:09

Dunc