Search code examples
asp.netvb.netviewstate

How can I prevent "Validation of viewstate MAC failed" error when user does not post back for 30+ minutes?


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.

I'm trying to find a way to prevent this error. It is occurring on my site when a user leaves the page open for 30+ minutes and fires an event that posts back. The way I understand this error and my issue is that the application pool has recycled and the viewstate is no longer valid. I'm not sure how to overcome this issue without keeping the session alive and wasting resources to do that... Any clever methods of completing this task?


Solution

  • According to this page there are 4 reasons why you might be getting this error:

    1. application is running in a farm (multi-server environment)
    2. worker process uses IIS 7.0* application pool identity
    3. application pool configured by using LoadUserProfile = false
    4. Page.ViewStateUserKey property has an incorrect value

    * Note: this is no longer the issue starting with IIS 7.5 and up, according to article.

    The big picture

    The big picture of the problem is that a cryptographic key used to encrypt view state data is not being persisted (for one of those or combination of those reasons above), hence new cryptographic key is being generated which does not match original one. There are a few ways in which you can persist this key (or have your application use the correct key). See solutions below.

    Solutions

    1. Manually set MachineKey in web.config
    2. Use aspnet_regiis utility to run managed application where machine keys will be persisted.
    3. Run PowerShell script to persist machine key in HKLM registry rather than in HKCU registry.
    4. Set LoadUserProfile = true to make HKCU registry hive be available to application.
    5. Check for correctness of Page.ViewStateUserKey property to see if consumed value matches the value when key was generated (that is if you use this property).

    This is a quick overview. For more details on any cause of the problem (as well as PowerShell script in #3) or solution of that problem please take a look at article to troubleshoot your particular case and to select most suitable for your purposes solution.