Viewstate timeout error - asp.net

I develop mostly for desktop so, I tend to think as WebForms as a web equivalent of WinForms. Unfortunetly this is not true.
Recently I have discovered that the Viewstate have some kind of timeout.
My problem is similar as I have read in most questions, in particular here (in my case is only around 5 to 10 minutes).
Here Microsoft says that one solution for this problem is:
<asp:Page EnableViewStateMac="False" />
However as we can read further they say:
Security Note:
This attribute should never be set to false in a production Web site,
even if the application or page does not use view state.
The view state MAC helps ensure the security of other ASP.NET functions
in addition to view state.
For this reason I don't want to set EnableViewStateMac to false and I have no access to my server (is shared hosting).
My question is: can we store the Viewstate between postbacks even if our page stay idle for a long time? If yes, how?
Thank you

The viewstate is encrypted using a machine key to ensure that it is not tampered with during postback. The machine key used to encrypt the viewstate is by default auto-generated and if the time out happens then the key's decryption will fail because the machinekey will get regenerated.
The machinekey is by default available at machine level config file.
<machineKey validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps"
validation="SHA1" decryption="Auto" />
To fix this, you can use your own defined machine key. You can generate using online tools as well, like this or through IIS.
How to add this machinekey to web.config can be read at MSDN.
It should be placed under the system.web section, like this -
<configuration>
<system.web>
<machineKey decryptionKey="Decryption key goes here,IsolateApps"
validationKey="Validation key goes here,IsolateApps" />
</system.web>
</configuration>

Related

Validation of viewstate MAC failed, but occurs on only 1 out of 2 webfarm servers (machine key is correct)

So I have something weird going on and i can not pin down exactly what is causing it. My asp.net project is live with session state on two production servers that are synced using the following command:
msdeploy -verb:sync -source:webserver,computername=%MACHINE%,username=Administrator,password=%PASSWORD% -dest:webserver 2<&1
The application is an asp.net 4.0 website that is run on two Server 2008 R2 web servers behind a load balanced configuration where the users are set to stick to one server once they connect. We have <MachineKey> set hardcoded with validation and decryption keys in the root site of the application and it is the same between both servers. My application is set up to forward exception events to our email system.
What is happening is that i am receiving the dreaded 'Validation of viewstate MAC failed' from the servers but even though the server load is 50/50 split the errors are coming in on a 99/1 split. So one web server is generating these errors considerably more often than the other one. This is strange considering the servers are synced and all configurations are identical.
I've done extensive searching on this problem and it seems quite difficult to find any solution that doesn't mention or do the following.
<MachineKey> is not identical between servers. (I know for a fact this is not my problem)
Setting enableViewStateMac=false or some other setting that jeopardizes the site security.
Make sure that all action tags on form inputs reference the same page they are placed on
Make sure the instance ID of the servers are the same (they are)
If the user clicks through the page before the entire page (viewstate) has been downloaded (my viewstate is set to render at the top of the page).
Issues with response.redirect and server.transfer
Now i have eliminated all except the last two as possible causes. My application has been running fine for over a year with no issues and right before these errors appeared i enabled SQL session state, migrated the project from .NET 3.5 to .NET 4.0, and set the set the server mode deployment mode to retail. I have tried recycling the application pools and performing an 'iis reset' to no avail.
Does anyone else have any suggestions as to what i can look at? Bottom line i do NOT want to fix this by opening up security holes in my site.
It appears this is happening to users right after they authenticate using forms authentication the first time they try to log in but i can not confirm this. I also have a theory that this might have to do with caching but i can't be sure on this either.
Here is the juicy bit from my web.config (i have removed some sensitive information)
<system.web>
<httpRuntime requestValidationMode="2.0"/>
<globalization culture="en-US" uiCulture="en-US" resourceProviderFactoryType="WebResourceFactory"/>
<compilation debug="true" defaultLanguage="c#" explicit="true" strict="true" targetFramework="4.0">
<assemblies>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="Login.aspx" protection="All" slidingExpiration="true"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<sessionState mode="SQLServer" sqlConnectionString="connection" compressionEnabled="true" />
<pages theme="Blue" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<machineKey validationKey="key" decryptionKey="key" decryption="3DES" validation="SHA1" />
</system.web>
EDIT:Emphasized that i'm using SQL session state with a load balancer set to prefer to route users to the server they started on.
There is an additional possibility that you have not added to your list - ViewStateUserKey.
I have seen issues with applications where the ViewStateUserKey was set to the Session ID on logon and (crucially) before any data is saved to the Session. Since ASP.NET does not persist Session IDs until one or more objects are saved to session this meant that the ID was constantly changing and the Viewstate was failing validation. Even if you have saved something to Session then the Session will be different on each server if you are using the default in-process model and not a state server or SQL session store (as you are doing). Any server specific value or value that is not readily predictable across servers used with ViewStateUserKey will of course also cause this problem.
Otherwise the most common causes of this issue I have seen is where an "Action" attribute is set on a form that is not the URL of the same page as the form (this catches out developers used to PHP or platforms that do not attempt to abstract away from HTTP), or missing Machine Key attributes in the Web.config in multi-server environments (which you seem to have covered).
Ok i appear to have fixed it, though i can not discern what exactly caused it so i will just list all the steps i performed in case someone else has this problem later on.
1 :
Installed these windows updates:
2:
My forms authentication cookie was set to persistent but my session cookie was set to the browser session. I set my forms authentication cookie to be browser session based.
3:
I copied my from the site config to the root of IIS. From all the documentation i could find it should not be necessary for me to do this because IIS should support multiple machine keys for different sites / applications.
4:
Rebooted the server.
That's it! I have not received the errors since then.

Has anyone encountered 'Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster..'error

I did some research on this and have tried out inserting:
<machineKey decryptionKey="A4B12CCDD50E95F8GB9GFH6JKAT4Y0U0I2OF2DF2AAFE5AB46189C,IsolateApps" validation="AES" validationKey="480CDF2AS9S9AS5CFDGF0GHFH9JJH4KHKAKLJ2L9F3SAS82A6C16911A29EF48903783F94529C21570AACB72766FB38CD4CE7B85B0ACE3149DC5FC1CCF1AA1CECE3579659996593B06,IsolateApps"/>
as a solution to this error:
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 time I get an error.
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Then it marks out the line in Config source:
<add name="DemographicDBEntities" connectionString="metadata=res://*/DemoGraph.csdl|res://*/DemoGraph.ssdl|res://*/DemoGraph.msl;provider=System.Data.SqlClient;provider connection string="data source=207.27.57.76,1433;initial catalog=DemographicDB;persist security info=False;user id=west;pwd=westhouseit;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<machineKey decryptionKey="A4B12CCDD50E95F8GB9GFH6JKAT4Y0U0I2OF2DF2AAFE5AB46189C,IsolateApps" validation="AES" validationKey="480CDF2AS9S9AS5CFDGF0GHFH9JJH4KHKAKLJ2L9F3SAS82A6C16911A29EF48903783F94529C21570AACB72766FB38CD4CE7B85B0ACE3149DC5FC1CCF1AA1CECE3579659996593B06,IsolateApps"/>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
Is the machine key tag well constructed? I put it in a tag all by itself.
I am hosting the application on an online host so I cannot generate any machine code with IIS 7.0. I have raised several tickets to no avail. Thanks for the assistance.
I don't think you can manually specify the key and include the IsolateApps option. It must be Autogenerate,IsolateApps or a specific value without the IsolateApps option.
See the MSDN documentation for details.
I believe what the issue is that IIS doesnt have access to your webconfig file.
Try this out, if it doesnt work take a look at the link below to see if you can try and error your issue.
1.Open control panel
2.Click on” program” link (not uninstall programs)
3.Click” turn windows features on/off” link
4.locate” Internet Information services IIS” in the pop up window and expand its node
5.Expand the” World Wide Web Service” node
6.Expand “Application Development Features” node
7.check the check box of”ASP.NET”
8.Then click ok button
Below is a very interesting link that would help you:
http://support.microsoft.com/kb/942055
Below is a link to a bug report that references Windows 2003 and .Net framework 3.5 and a web garden setup.
Nothing says that the problem is restricted to Win 2003 or even framework 3.5. In a web garden situation, one can imagine that the viewstate errors would happen VERY frequently, not just when the pool recycles (as we experienced).
http://connect.microsoft.com/VisualStudio/feedback/details/412881/net-3-5-installer-breaks-web-gardens-when-used-with-custom-application-pool-identity
To fix the metabase and registry permissions issues, we simply executed the following on our web server:
\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga domain\useraccount
We then recycled the app pool one more time to regenerate the viewstate validation key.
Whether or not this works in your situation will depend on specific details of your situation.

ASP.NET MVC3 Publish settings in web.config

I have published an ASP.NET MVC3 site. It runs great. However, looking back at my web.config file, I was not sure if some of the values I used are correct for publishing versus for developing. These configurations are in the <system.web> section.
...
<system.web>
<httpRuntime requestValidationMode="2.0" executionTimeout="200" maxRequestLength="20000000"/>
<compilation debug="true" targetFramework="4.0">
...
I read here ( http://msdn.microsoft.com/en-us/library/e1f13641.aspx ) that using debug=true in compilation will disregard the executionTimeout of 200, and use a default value of 110. This seems to be the case, and the site is setup to allow very large amounts of files to be uploaded all at once. However, with only 110 seconds, not much can be uploaded.
My question is this: Is the correct setting to publish a live site for debug "false"? In addition, is requestValidationMode="2.0" still safe to use considering asp.net is now on version 4 (soon to be 4.5)?
Validationmode 2.0 is not the framework version and can stay like that.
Put debug=false and you are fine.
requestValidationMode... As far as I'm aware, this has to be set to 2.0 if you want to allow special characters (<, >, % etc.) in request data to pass ASP.NET's request validation at all. requestValidationMode="2.0" means "only enforce validation on pages (i.e. .aspx), rather than on every request (as was introduced in 4.0). That allows ASP.NET MVC to take over the validation - and hence also lets you turn it off for specific requests.
Is it safe? It is, if you've made sure that any actions or controllers that have [ValidateInput(false)] applied or models with [AllowHtml] have been properly secured against attacks. Imran Baloch has a full explanation here.
And yes, debug should be "false" for several reasons, including performance and memory usage. Also, debug="true" changes the default cache policy for static files to never cache the files in the browser, meaning tons of redundant requests for scripts, CSS etc.
As for the image upload, other than the suggestions given, check in Event Viewer that it's not really the application pool recycling for one reason or other, rather than an execution timeout.

Asp.net Validation of viewstate MAC failed

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?
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:
Open IIS and select a website to get this screen:
Double click the Machine Key icon to get this screen:
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.
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
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.
This solution worked for me in ASP.NET 4.5 using a Web Forms site.
Use the following site to generate a Machine Key (for example only use secure method in production): http://www.blackbeltcoder.com/Resources/MachineKey.aspx
Copy Full Machine Key Code.
Go To your Web.Config File.
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.
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
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="..." />
WHAT DID WORK FOR ME
Search the web for "MachineKey generator"
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" />
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
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();
});
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.
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" />
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.
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="/" />
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)
<system.web>
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
</system.web>
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:
Open App pool of you website on IIS.
Go to Advance settings on right hand pane.
Scroll down to Process Model
Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.
Then try again . It will solve your issue.
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.
Thats worked for me
Just add it :
between
system.web section
<system.web>
</system.web>

Why does a change of Session State provider lead to an ASPx page yielding garbage?

I have an aspnet webapp which has worked very well up until now.
I was recently asked to explore ways of making it scale better.
I found that seperation of database and Webapp would help.
Further I was told that if I changed my session providing mechanism to SQLServer, I would be able to duplicate the Web Stack to several machines which could each call back to the state server allowing the load to be distirbuted better.
This sounds logical. So I created an ASPState database using ASPNet_RegSQL.exe as detailed in many locations across the web and changed the web.config on my app from:
<sessionState mode="InProc" cookieless="false" timeout="20" />
To:
<sessionState mode="SQLServer"
sqlConnectionString="Server=SomeSQLServer;user=SomeUser;password=SomePassword"
cookieless="false" timeout="20" />
Then I addressed my app, which presented me with its logon screen and I duly logged in.
Once in I was presented, with a page that was not with the page I was expecting.
I can change the sessionstate back and forth. This problem goes away and then comes back based on which set of configuration I use.
Why is this happening?
Nice error Dude :)
Probably a red-herring, but what are you storing in Session state?
When you move from InProc to SQL Server, the stuff you store in SQL must be Serializable (I think)
Use Fiddler to see what's really going on over the wire. To me it looks like your app is sending back an image when the browser is expecting HTML.

Resources