Server Error in '/' Application. Validation of viewstate MAC failed or AntiForgeryToken Exception in ASP.NET MVC or .NET Core Print

  • asp.net viewstate, mac failed, validation, unhandled exception, machineKey
  • 2

You receive the following message from time to time on your ASP.NET Website:

 

Server Error in '/' Application.

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.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: 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.

 

OR

 

System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not
supplied or was invalid.

 

Resolution:

This error is usually caused by the Application Pool process or the server recycling. By default, ASP.NET encrypts the viewstate using an Autogenerated Key when the process spins up. The problem comes when a client (browser) sends the request with a viewstate encrypted with the key generated by another worker process. Since the key is different, ASP.NET will not be able to decrypt the viewstate and it will throw the above error.

There are several ways to get around this problem:

1) Host your site on a server that never restarts or recycles. Obviously, this is not possible!

2) Configure ASP.NET to not use Auto-Generated Key but rather a predefined key. This is the preferred method.

To do this, follow these steps:

a) Either build your own Key Generator or use this tool (ASP.NET Machine Key Generator (blackbeltcoder.com)). We highly recommend you use the online tool. So assuming you will use the online tool:

b) In the online tool, simply click the  "Generate Keys" button.

c) Copy the content in the textbox into your site's web.config file. The machineKey node should be within <system.web>

eg.

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<machineKey
validationKey="3547D113BBF1E9B415B44A7D56A29A17FA3888431B277AEFFB5C700E5934B46C7413738375C46FD2A0D0DDF80974FCA4E0A4E93024696A55140F02F8573E0240"
decryptionKey="262F6731B3D2AF8E36FFEDA6BB7902BEBF6A0E6B44A8D5BE7380F044EDC4D768"
validation="SHA1" decryption="AES"
/>
</system.web>
</configuration>


Was this answer helpful?

« Back