aspx page gives viewstate error - asp.net

I have a simple aspx page with one grid view. When deployed on server, and accessed through that machine, it works fine. However, when connected through load balancer, we get this error ( when click on any button). The page however refreshes when pressed F5.
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.
Any idea what is happening here???

You should set the machineKey on your web.config to be the same for all load balanced servers.
The machine key is used to encrypt, validate, hash, etc. all ASP.NET internal stuff. When the ViewState is created on one machine it is created with the machine key for that machine the other machine cannot validate it because its key is different. Despite the fact that it is called machine key it can be set per application.
There are multiple generators for machine keys (it is not hard to write one). Here is the first Google hit:
http://aspnetresources.com/tools/machineKey

Added enableViewStateMAC = false on the page directive

Related

Getting ViewStateException: Invalid viewstate while Machine keys are the same

I have 8 host behind LB and all of them are single process(not web garden). Despite setting all of them with the same machine key from iis as shown below, I'm still getting Invalid viewstate exception rarely.
There similar questions but none of them helped me(I've no server with pending updates or restart as in the other questions or i'm not using server.execute etc). So please don't flag as duplicate. Are there any alternative ways to prevent this exception?
Thx
Normally, This is because of the difference in Machine keys in different servers. We use Web Farm for High availability. In this case, if a Client sends a request then the Load balancer decides, which webserver to serve the request. It happens several times that another request might be served by another server. So here is the issue.
As we know, view stat is Client-side state management techniques and the data travels with the request and response. So if the view state is encrypted with some machine key and in other requests if handled by another server and that has different machine key, it would not be able to decrypt it and will through the error.
Every server generates a new key when it is set auto. and even sometimes any recycle of the app domain will generate a new key when it is set to auto. It means we cannot use the default auto-generated key. So here the solution is to use a specific key in the machine.config to prevent automatic key generation on each process start.
One another flexible approach, however, would be to add a MachineKey section to the web.config file of your web site. This would not require to make the changes on every web server.
another way is you could try to set below code in machine.config:
enableViewStateMac="false"

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?
According to this page there are 4 reasons why you might be getting this error:
application is running in a farm (multi-server environment)
worker process uses IIS 7.0* application pool identity
application pool configured by using LoadUserProfile = false
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
Manually set MachineKey in web.config
Use aspnet_regiis utility to run managed application where machine keys will be persisted.
Run PowerShell script to persist machine key in HKLM registry rather than in HKCU registry.
Set LoadUserProfile = true to make HKCU registry hive be available to application.
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.

IsPostBack is false when transfering to different server in server farm?

I have a asp.net website that is deployed on two servers. In front of the servers there's a load balancer that distribute requests to the two servers. To store the session we use SQL Server.
My problem is that if the user go to the page, press a button and then by the load balancer happens to be routed to the other server that request wont be recognized as a postback? Why is that, shouldn't it work just fine even with postbacks as long as the servers share the same machine keys?
Details:
Both servers have the same machine key configured, and I verified that the actual session is the same on both servers by a small debug page I made that sets and prints out a session object.
To further verify the keys and Id I printed out the values of HttpRuntime.AppDomainAppId and a hashed machinekey (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey") and the sessionId Session.SessionID and got the same output on both servers. I used Session Debug page as a base for this. Its output looks something like this (I replaced my actual machinkey hash and session id with dummy values):
Current DataTime: 2012-07-20 10:52:58
Current Session Mode: SQLServer
HttpRuntime.AppDomainAppId: /LM/W3SVC/5/ROOT
Hashed with the MachineKey: HjtOPW5dfoihdlkd+SdsfkEWfs0=
Local Machine Name: 127.0.0.1
Current Session ID: 2alsudhsdkjlhcmnsdfkhsdf
The ID for the site, found in IISMgr under Advanced Settings on the site is the same on all servers.
As long as I stay on the same server everything works as expected.
When I run the page locally (first request to web farm, then route second button click to localhost by fiddler), I get the same behaviour
Stepping through the code and reading up on the IsPostBack property it seems my problem is that this._fPageLayoutChanged on the Page is true. However, if I understand things correctly it should be false when a postback happens? SO Question on its implementation
Both servers run IIS 7.
Both servers run Windows Server Web with SP2 and the same windows update updates installed. My local dev machine on the other hand runs Windows 7.
Turns out that adding a manual entry of the Machinekey in the web.config fixed the problem. Very strange as I checked its global value and also the hash as detailed in the question but now it works.
I take that back. After our last release the problem is back, so the machinekey addition did not help at all.

Validation of viewstate MAC failed when on page for 20+ minutes

If you open a web page on one of the websites hosted on our server, leave it for 20 minutes and then submit a form, a Validation of viewstate MAC failed. error occurs.
What possible reasons could there be for this?
There's a few reasons this can happen:
Auto-Generated Machine Keys:
If your application pools have the default idle timeout of 20 minutes AND you're using auto-generated validation and decryption keys then each time the pool starts it will generate a new set of keys. This invalidates the browser's encrypted viewstate. You'll also find that forms authentication tickets for persistent tickets will also become invalid.
To overcome this set these keys to fixed values in:
`c:\%systemroot%\microsoft.net\framework\v2.0.50727\CONFIG\machine.config`
You need to add the <machineKey> configuration element to the <system.web> section. There's a pretty good article here that explains how to do this:
How To: Configure MachineKey in ASP.NET 2.0
Scroll down to the section on "Web Farm Deployment Considerations" and Generate Cryptographically Random Keys.
If you're running a load balanced web farm you also need to set each server's machine key to exactly the same value.
Incorrect form action value (3.5SP1):
There's also a case (post 3.5SP1) where if you set the action attribute of your ASP.NET form to something other than the page being posted back to and you're not using crosspage postbacks then you will get this error. But you'd see this right away:
Validation of viewstate MAC failed after installing .NET 3.5 SP1
Timing/Long Running Pages:
There's also an edge case for pages that take a long time to render where if the page is partially rendered and a postback occurs:
Validation of viewstate MAC failed error
Root Cause This exception appears because Controls using DataKeyNames
require Viewstate to be encrypted.
When Viewstate is encrypted (Default
mode, Auto, is to encrypt if controls
require that, otherwise not), Page
adds
field just before closing of the
tag. But this hidden field
might not have been rendered to the
browser with long-running pages, and
if you make a postback before it does,
the browser initiates postback without
this field (in form post collection).
End result is that if this field is
omitted on postback, the page doesn't
know that Viewstate is encrypted and
causes the aforementioned Exception.
I.E. page expects to be fully-loaded
before you make a postback.
It's taken us a while to find the answer to this as I had been informed that another IIS7 server I was comparing it to had been setup in the same way, by the same person.
It turns out the server with the websites which were receiving this error had been setup using Plesk, whereas the other server had not been.
It seems Plesk sets the Idle-Timeout to 5 minutes on the application pools, which is what was causing this error.
To change this do the following:
Open IIS
Click on application pools node
Locate your web application's application pool
Right-Click and select Advanace Settings
Set the Idle Time-out(minutes) property to 0 or increase it to 30+ minutes
For me, this solved the problem:
I've set LoadUserProfile = True in the application pool to make HKCU registry hive be available to the application.
Note: This is compatible with IIS 7.0+
I ran into this problem, and the scenario was a single web server hosting a very basic ASP.Net application. After struggling a lot I found this post, and that helped me to understand that the problem was the worker process getting recycled.
I find this quite harsh, as it's a scenario that an application might face and such a core error prevents you to handle it properly. As far I could see, this is originated because the default configuration for handling this keys will use the machine.config that states that keys are automatically generated and isolated per application. I think in this cases ASP.Net a temporary key and store it at the worker process level, and when that worker process is gone the issue arises and can't be handled.
The alternative of configuring the machine key solves the problem, clearly is better to set it on the web.config file rather the whole machine.config to keep it at the lowest granularity level.
Another option is to disable the view state MAC check, also through web.config. It will depend on the security level of your application and the risk of having the view state tampered with.
And the best option is to avoid using view state with a MVC application.
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
As I found out, there was a <base ....
tag in header part of my master page, that I added in last tie and before publishing. This tag specify a default URL and a default target for all links on a page. This was the main cause of the fault, this time.

Error using viewstate (in a cluster?)

I am getting the follwing error,please tell me why this error is coming
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.
this can happen when you post a form which in the meantime has been updated on the server, or the app has been recycled in IIS.
By default Viewstate is generated based on the MAC address of the machine that the web server is running on - this can cause problems when load balancing web traffic across a web farm or cluster as there is a chance that a pages post back request might get processed by a different machine from the one that originally generated the viewstate token, which will cause the exception that you see above.
If your running a web farm / cluster then the answer is the <machineKey> configuration element - if you set this to the same algorithm / key for each of the machines then viewstate is generated based on this key instead of the MAC address of the machine, preventing the above problems.
This blog article probably explains it better than I just did.

Resources