Validation of viewstate MAC failed when on page for 20+ minutes - asp.net

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.

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.

Increasing Session TimeOut

Site hosted via IIS 7.0
I would like to set my session time-out to 9 hours in my ASP.NET application.
This has been set at web.config
<sessionState timeout="540"></sessionState>
But, as I understand, if the timeout is set as 20 minutes inside the IIS where the website is hosted, setting an extended session state will be of no use.
Firstly, I would like to confirm whether this assumption is right.
The problem is that I do not have access to the IIS of my shared hosted web server.
Now, after some research, I came up with another solution in code project. This sounds like a wonderful idea. The idea is to insert an iframe to master page. The iframe will contain another page with meta refresh less than 20 minutes.
Response.AddHeader("Refresh", "20");
This idea seemed good for me. But the article is 7 years old. Plus at comments section a user complaints that this won't work if the page is minimized and I am worried that the same happens when my pages tab is not active.
I would like to know these things
Whether the refresh method will work for my scenario , even if the page is minimized?
Are there any other methods that could increase session time out that overrides IIS timeout setting?
Also I read some questions in Stack Overflow where the answers state that the IIS session timeout is for clasic ASP pages. Then why is not my extended timeout not firing?
Firstly, I would like to confirm whether this assumption is right.
Yes, this assumption is absolutely right in case you are using in-memory session state mode. In this case the session is stored in memory and since IIS could tear down the AppDomain under different circumstances (period of inactivity, CPU/memory tresholds are reached, ...) the session data will be lost. You could use an out-of-process session state mode. Either StateServer or SQLServer. In the first case the session is stored in the memory of a special dedicated machine running the aspstate Windows service and in the second case it is a dedicated SQL Server. The SQL Server is the most robust but obviously the slowest.
1) Whether the refresh method will work for my scenario , even if the page is minimized?
The hidden iframe still works to maintain the session alive but as I said previously there might be some conditions when IIS unloads the application anyway (CPU/memory tresholds are reached => you could configure this in IIS as well).
2) Are there any other methods that could increase session time out that overrides IIS timeout setting?
The previous method doesn't increase the session timeout. It simply maintains the session alive by sending HTTP requests to the server at regular intervals to prevent IIS from bringing the AppDomain down.
3) Also I read some questions in Stack Overflow where the answers state
that the IIS session timeout is for clasic ASP pages. Then why is not
my extended timeout not firing?
There is no such thing as IIS session timeout. The session is an ASP.NET artifact. IIS is a web server that doesn't know anything about sessions.
Personally I don't use sessions in my applications. I simply disable them:
<sessionState mode="Off"></sessionState>
and use standard HTTP artifacts such as cookies, query string parameters, ... to maintain state. I prefer to persist information in my backend and retrieving it later using unique ids instead of relying on sessions.

Losing Session State

I have an ASP.net application where Users aren't able to successfully complete certain actions, for reasons, I'm assuming, can only be related to losing their session (which is where I maintain their current user information, and how determine whether they are logged in)
I'm at a loss as to why they would lose their session, so my first question is:
What (in general) would cause a user to lose their session in ASP.net?
and since I don't know when a user loses their session and can't reproduce it myself:
How can I track when I user loses their session
Below is my sessionState config for reference
<sessionState
mode="InProc"
cookieless="false"
cookieName="My.Site.Com"
timeout="480"/>
A number of things can cause session state to mysteriously disappear.
Your sessionState timeout has expired
You update your web.config or other file type that causes your AppDomain to recycle
Your AppPool in IIS recycles
You update your site with a lot of files, and ASP.NET proactively destroys your AppDomain to recompile and preserve memory.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
By default, IIS sets AppPools to turn themselves off after a period of inactivity.
By default, IIS sets AppPools to recycle every 1740 minutes (obviously depending on your root configuration, but that's the default)
In IIS, check out the "Advanced Settings" of your AppPool. In there is a property called "Idle Time-out". Set that to zero or to a higher number than the default (20).
In IIS, check the "Recycling" settings of your AppPool. Here you can enable or disable your AppPool from recycling. The 2nd page of the wizard is a way to log to the Event Log each type of AppPool shut down.
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
http://web.archive.org/web/20100803114054/http://surrealization.com/sample-code/getnotifiedwhenapppoolrecycles/
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
http://msdn.microsoft.com/en-us/library/system.web.configuration.compilationsection.numrecompilesbeforeapprestart.aspx
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
I was having a situation in ASP.NET 4.0 where my session would be reset on every page request (and my SESSION_START code would run on each page request). This didn't happen to every user for every session, but it usually happened, and when it did, it would happen on each page request.
My web.config sessionState tag had the same setting as the one mentioned above.
cookieless="false"
When I changed it to the following...
cookieless="UseCookies"
... the problem seemed to go away. Apparently true|false were old choices from ASP.NET 1. Starting in ASP.Net 2.0, the enumerated choices started being available. I guess these options were deprecated. The "false" value has never presented a problem in the past - I've only noticed in on ASP.NET 4.0. I don't know if something has changed in 4.0 that no longer supports it correctly.
Also, I just found this out not long ago. Since the problem was intermittent before, I suppose I could still encounter it, but so far it's working with this new setting.
In my case setting AppPool->AdvancedSettings->Maximum Worker Proccesses to 1 helped.
Your session is lost becoz....
JUST MAKE SURE THERE ARE NO RUNTIME ERRORS, ANY FATAL EXCEPTION WOULD
KILL THE SESSION!
In Microsoft stack, Visual Studio - put Ctrl + Alt + E - All Exceptions ON, then run the code in Debugging mode. Any Fatal ones are THE reason for session loss..
You could add some logging to the Global.asax in Session_Start and Application_Start to track what's going on with the user's Session and the Application as a whole.
Also, watch out of you're running in Web Farm mode (multiple IIS threads defined in the application pool) or load balancing because the user can end up hitting a different server that does not have the same memory. If this is the case, you can switch the Session mode to SQL Server.
I was only losing the session which was not a string or integer but a datarow.
Putting the data in a serializable object and saving that into the session worked for me.
Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses was set to 2 and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.
Solution was to Change MaximumWorkerProcesses to 0 in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses.
Dont know is it related to your problem or not BUT Windows 2008 Server R2 or SP2 has changed its IIS settings, which leads to issue in session persistence. By default, it manages separate session variable for HTTP and HTTPS. When variables are set in HTTPS, these will be available only on HTTPS pages whenever switched.
To solve the issue, there is IIS setting. In IIS Manager, open up the ASP properties, expand Session Properties, and change
New ID On Secure Connection to False.
I had same problem by losing sessions. every time , every page reload, my sessions clear and by new reload any page, my sessions returned by valid value...
i fixed it by change MaximumWorkerProcesses from 0 to 1 in iis
I was struggling with this issue for 14 days.
Here's what helped me:
Check your recycling options in App Pool > Advanced settings. Turn off all of the options so it won't recycle on its own.
Check your web.config file for the executionTimeout property under httpRuntime and increase its value.
Check your web.config file for the timeout property under sessionState and increase its value (I set it to 300 minutes).
Go to the server's event log and check the Application log for unhandled exceptions that may cause the worker process to crash. Fix them in your code or use try and catch to eliminate this crash.
Try changing the value of your maximum worker process from 0 to 1 or the other way around, this may also solve this issue.
In my case, session state was loosing due to Load Balancer. Session was storing in one server and Load balancer was redirecting next call to another server where session state was missing.

ASP.NET app having viewstate corrupted every few minutes

I'm having a problem with a web app I'm managing. Users starting receiving the following error occasionally:
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.
The problem is that it's not a cluster - it's a single Windows 2003 server. After digging around, it appears that adding a machineKey section and some extra attributes to the Pages directive in my web.config resolves this error:
<machineKey validationKey='MACHINE KEY SNIPPED'
decryptionKey='DECRYPTION KEY SNIPPED'
validation='SHA1'/>
<pages validateRequest="true" enableEventValidation="false">
After changing these two things in my web.config, the error goes away, but now I have a new problem - Instead of an error that my viewstate is invalid, the app just "Forgets" who my user is, and sends them back to the login page. Now, the users are browsing through the application, and then they're unexpectedly sent to the login page, even after they've already been logged in for a few minutes. While I can't force this to happen, it usually happens within visiting 10-12 different pages, so pretty frequently.
I'd love a resolution to this - does anybody know what else might be causing the viewstate error on a single server, or what I can do to ensure that it's validated properly?
It sounds as though the worker process is recycling itself (assuming you're storing session state in-process). Picking a fixed key means that the viewstate is still valid when the process comes back up, but you've lost the session state. You could try storing the session state in a database, but I'd be more concerned to fix the underlying problem. Does your application suddenly allocate vast amounts of memory, or anything like that? Is there anything suspicious in the event log?
It turned out that this began happening when I added additional worked processes to the app pool that was running our application. Because the session state was being stored InProc (and not in a state service or a SQL Server), it was losing track of who the user was when it switched them between working processes. For now, dropping the number of processes on our server back to one corrected the problem, since raising it didn't seem to have any improvement in the first place.

Resources