50

I am receiving the following error at certain times on asp.net website.

 Sys.WebForms.PageRequestManagerServerErrorException: 
 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.

When page refresh goes,no problem.How can I solve this problem?

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Arbelac
  • 1,698
  • 6
  • 37
  • 90
  • 1
    Some more info is needed. Is this on your single, developer machine? A production server? Are there more than one production server (ie a web farm) ? – Pure.Krome Apr 30 '11 at 09:49
  • I have the same error in my dev team. Some computers get this error and some others don't. Anybody can provide an answer ? (None of the two posted can solve my problem) – Apolo Apr 15 '15 at 15:16
  • I saw this post on MSDN (http://blogs.msdn.com/b/webtopics/archive/2009/05/13/viewstate-exception-may-come-with-action-attribute-in-form-tag-post-net-framework-3-5-sp1.aspx), you have code to reproduce. The solution provided (remove the action attribute of the form) is not good (because my form would go nowhere) – Apolo Apr 15 '15 at 15:18

17 Answers17

34

Microsoft says to never use a key generator web site.

Like everyone else here, I added this to my web.config.

<System.Web>
    <machineKey decryptionKey="ABC123...SUPERLONGKEY...5432JFEI242" 
                validationKey="XYZ234...SUPERLONGVALIDATIONKEY...FDA" 
                validation="SHA1" />
</system.web>

However, I used IIS as my machineKey generator like so:

  1. Open IIS and select a website to get this screen:

enter image description here

  1. Double click the Machine Key icon to get this screen:

enter image description here

  1. Click the "Generate Keys" link on the right which I outlined in the pic above.

Notes:

  • If you select the "Generate a unique key for each application" checkbox, ",IsolateApps" will be added to the end of your keys. I had to remove these to get the app to work. Obviously, they're not part of the key.
  • SHA1 was the default encryption method selected by IIS and if you change it, don't forget to change the validation property on machineKey in the web.config. However, encryption methods and algorithms evolve so please feel free to edit this post with the updated preferred Encryption method or mention it in the notes and I'll update.
mybrave
  • 1,662
  • 3
  • 20
  • 37
Tony L.
  • 17,638
  • 8
  • 69
  • 66
  • 3
    I find this approach far better than the powershell approach suggested by microsoft (keep it simple) and a lot more thrustworthy than those webpages that autegenerate keys. – Cleptus May 28 '18 at 13:41
30

If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:

<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />

Put it under the <system.web> tag.

The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script: https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa

techvice
  • 1,315
  • 1
  • 12
  • 24
Maged Samaan
  • 1,742
  • 2
  • 19
  • 39
27

I had this problem, and for me the answer was different than the other answers to this question.

I have an application with a lot of customers. I catch all error in the application_error in global.asax and I send myself an email with the error detail. After I published a new version of my apps, I began receiving a lot of Validation of viewstate MAC failed error message.

After a day of searching I realized that I have a timer in my apps, that refresh an update panel every minute. So when I published a new version of my apps, and some customer have left her computer open on my website. I receive an error message every time that the timer refresh because the actual viewstate does not match with the new one. I received this message until all customers closed the website or refresh their browser to get the new version.

I'm sorry for my English, and I know that my case is very specific, but if it can help someone to save a day, I think that it is a good thing.

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Sébastien
  • 271
  • 3
  • 2
9

This solution worked for me in ASP.NET 4.5 using a Web Forms site.

  1. Use the following site to generate a Machine Key (for example only use secure method in production): http://www.blackbeltcoder.com/Resources/MachineKey.aspx
  2. Copy Full Machine Key Code.
  3. Go To your Web.Config File.
  4. Paste the Machine Key in the following code section:
    <configuration>
      <system.web>
        <machineKey ... />
      </system.web>
    </configuration> 

You should not see the viewstate Mac failed error anymore. Each website in the same app pool should have a separate machine key otherwise this error will continue.

TsTeaTime
  • 881
  • 1
  • 13
  • 34
  • I receive this error: `It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.` Idk what this means. – AskYous Apr 19 '16 at 15:29
  • Are you using a Web Form site on asp.net? – TsTeaTime Apr 19 '16 at 15:31
  • Do not use online tools to generate keys – VSB Jan 19 '23 at 08:32
  • @VSB I've noted that they should use a secure method for production. – TsTeaTime Feb 02 '23 at 03:14
8

Dear All with all respict to answers up there there are case gives this error when web.config value is

<httpCookies httpOnlyCookies="true" requireSSL="true"/>

and link is http not https

Omar Kamel
  • 155
  • 1
  • 8
5

On multi-server environment, this error likely occurs when session expires and another instance of an application is resorted with same session id and machine key but on a different server. At first, each server produce its own machine key which later is associated with a single instance of an application. When session expires and current server is busy, the application is redirected like, via load balancer to a more operational server. In my case I run same app from multiple servers, the error message:

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

Defining the machine code under in web.config have solve the problem. But instead of using 3rd party sites for code generation which might be corrupted, please run this from your command shell: Based on microsoft solution 1a, https://support.microsoft.com/en-us/kb/2915218#AppendixA

# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
  [CmdletBinding()]
  param (
    [ValidateSet("AES", "DES", "3DES")]
    [string]$decryptionAlgorithm = 'AES',
    [ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
    [string]$validationAlgorithm = 'HMACSHA256'
  )
  process {
    function BinaryToHex {
        [CmdLetBinding()]
        param($bytes)
        process {
            $builder = new-object System.Text.StringBuilder
            foreach ($b in $bytes) {
              $builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
            }
            $builder
        }
    }
    switch ($decryptionAlgorithm) {
      "AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
      "DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
      "3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
    }
    $decryptionObject.GenerateKey()
    $decryptionKey = BinaryToHex($decryptionObject.Key)
    $decryptionObject.Dispose()
    switch ($validationAlgorithm) {
      "MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
      "SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
      "HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
      "HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
      "HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
    }
    $validationKey = BinaryToHex($validationObject.Key)
    $validationObject.Dispose()
    [string]::Format([System.Globalization.CultureInfo]::InvariantCulture,
      "<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
      $decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
      $validationAlgorithm.ToUpperInvariant(), $validationKey)
  }
}

Then:

For ASP.NET 4.0

Generate-MachineKey

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />

For ASP.NET 2.0 and 3.5

Generate-MachineKey -validation sha1

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />

Zly-Zly
  • 167
  • 2
  • 8
  • You do this on the server hosting the website ? I have a hosting plan which is a shared one. My website can be hit by different machines on different locations / network/ – FunMatters May 19 '18 at 06:01
  • Yes, on web app server in your web.config – Zly-Zly May 31 '18 at 11:07
  • Tks. I have managed to update the web.config with server machine keys which where supplied by my hosting company. – FunMatters May 31 '18 at 17:10
4

WHAT DID WORK FOR ME

  1. Search the web for "MachineKey generator"

  2. Go to one of the sites found and generate the Machine Key, that will look like... (the numbers are bigger)
    ...MachineKey
    validationKey="0EF6C03C11FC...63EAE6A00F0B6B35DD4B" decryptionKey="2F5E2FD80991C629...3ACA674CD3B5F068" validation="SHA1" decryption="AES" />

  3. Copy and paste into the <system.web> section in the web.config file.

If you want to follow the path I did...


https://support.microsoft.com/en-us/kb/2915218#AppendixA
Resolving view state message authentication code (MAC) errors Resolution 3b: Use an explicit <machineKey>
By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element.


http://blogs.msdn.com/b/amb/archive/2012/07/31/easiest-way-to-generate-machinekey.aspx
Easiest way to generate MachineKey - Ahmet Mithat Bostanci - 31 Jul 2012 You can search in Bing for "MachineKey generator" and use an online service. Honestly...


http://www.blackbeltcoder.com/Resources/MachineKey.aspx

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • 1
    The MS support link you gave strong discourages online MachineKey Generators https://support.microsoft.com/en-us/kb/2915218#AppendixA – Tony L. Feb 25 '16 at 05:07
4

my problem was this piece of javascript code

$('input').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});

Turns it was messing with viewstate hidden field so I changed it to below code and it worked

$('input:visible').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});
irfandar
  • 1,690
  • 1
  • 23
  • 24
0

This error message is normally displayed after you have published your website to the server.

The main problem lies in the Application Pool you use for your website.

Configure your website to use the proper .NET Framework version (i.e. v4.0) under the General section of the Application Pool related to your website.

Under the Process Model, set the Identity value to Network Service.

Close the dialog box and right-click your website and select Advanced Settings... from the Manage Website option of the content menu. In the dialog box, under General section, make sure you have selected the proper name of the Application Pool to be used.

Your website should now run without any problem.

Hope this helps you overcome this error.

Nanan
  • 17
  • 2
  • Although these are helpful configuration tips, telling the TC "Your website should now run without any problem" is misleading. The real answer does lie within the machineKey as stated in other answers. – DanM7 Oct 02 '12 at 16:30
  • 3
    Changing the identity from ApplicationPoolIdentity to NetworkService gives IIS way more permissions than it needs. This is again decreasing security to fix the problem. Please read the following for further explanation, http://www.iis.net/learn/manage/configuring-security/application-pool-identities – randomperson25 Feb 14 '13 at 20:24
0

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.

Answer :

<machineKey  decryptionKey="2CC8E5C3B1812451A707FBAAAEAC9052E05AE1B858993660" validation="HMACSHA256" decryption="AES" validationKey="CB8860CE588A62A2CF9B0B2F48D2C8C31A6A40F0517268CEBCA431A3177B08FC53D818B82DEDCF015A71A0C4B817EA8FDCA2B3BDD091D89F2EDDFB3C06C0CB32" />
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
0

I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.

aydin
  • 1
  • That's weird. Probably enabling sorting needs the data keys to be included in view state and asp.net encrypts it. Hence you get the validation error. – Ε Г И І И О Feb 13 '19 at 10:08
0

I am not sure how this happened but I started to get this error in my internal submit form pages. So when ever I submit something I'm getting this error. But the problem is this website is almost working 5-6 years. I don't remember I made an important change.

None of the solutions worked for me.

I have setup a machine key with the Microsoft script and copied into my web.config

I have executed asp.net regiis script.

aspnet_regiis -ga "IIS APPPOOL\My App Pool"

Also tried to add this code into the page:

enableViewStateMac="false"

still no luck.

Any other idea to solve this issue?

UPDATE:

Finally I solved the issue. I had integrated my angular 4 component into my asp.net website. So I had added base href into my master page. So I removed that code and it is working fine now.

<base href="/" />
Sam Salim
  • 2,145
  • 22
  • 18
  • For anyone else wanting to try `enableViewStateMac="false"` I think its been deprecated: https://blogs.msdn.microsoft.com/webdev/2014/09/09/farewell-enableviewstatemac/ Quote: "All versions of the ASP.NET runtime 1.1 – 4.5.2 now forbid setting <%@ Page EnableViewStateMac=”false” %> and ." – Jeff Mergler Jun 26 '18 at 05:00
0

There are another scenario which was happening for my customers. This was happening normally in certain time because of shift changes and users needed to login with different user. Here is a scenario which Anti forgery system protects system by generation this error:

1- Once close/open your browser. 2- Go to your website and login with "User A" 3- Open new Tab in browser and enter the same address site. (You can see your site Home page without any authentication) 4- Logout from your site and Login with another User(User B) in second tab. 5- Now go back to the first Tab which you logged in by "User A". You can still see the page but any action in this tab will make the error. Because your cookie is already updated by "User B" and you are trying to send a request by an invalid user. (User A)

0
<system.web>
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
</system.web>
Machavity
  • 30,841
  • 27
  • 92
  • 100
Ya Kutty
  • 31
  • 3
0

I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.

Following steps help me to fix the issue:

  1. Open App pool of you website on IIS.
  2. Go to Advance settings on right hand pane.
  3. Scroll down to Process Model
  4. Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.

enter image description here

Then try again . It will solve your issue.

Ashish Thakur
  • 213
  • 2
  • 12
0

I've experienced the same issue on our project. This Microsoft support web page helped me to find the cause. And this solution helped to sort out the issue.

In my case the issue was around ViewStateUserKey as Page.ViewStateUserKey property had an incorrect value (Caused 4 in here). Deleting localhost certificates and recreating them by repairing IIS Expres as mentioned in here fixed the issue.

CharithJ
  • 46,289
  • 20
  • 116
  • 131
-1

Thats worked for me

Just add it : between system.web section <system.web>

</system.web>