invalid viewstate error - OnPreRender - asp.net

I'm getting 100+ errors per day on my website with System.Web.HttpException: Invalid viewstate.
The website is asp.net 3.5 running on iis6 , not running in a web-garden/web-farm , single server.
Here are a few sample errors.
Machine: ML Framework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889
Source: http://www.domain.com/WebResource.axd?d=z5VmXXoSLLpQHoPictureAlert
Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Machine: MLFramework Version: 2.0.50727.3603 Assembly Version: 6.5.3664.33889
Source: http://www.mydomain.com/ScriptResource.axd?d=SE0Ej7OlEAx91j2Cjv_6KkRPplqT-5wB4M7CZPdGdGn3LahLwqlRPApUcdxBsbFXYHZ91Q76FHAHWgHs8SmOC4zemr7
siym0QY0rF3XtJTu%3C/a%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Ca%20id=
Exception: System.Web.HttpException: Invalid viewstate. at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at
System.Web.UI.Page.DecryptString(String s) at System.Web.Handlers.ScriptResourceHandler.DecryptParameter(NameValueCollection queryString) at
System.Web.Handlers.ScriptResourceHandler.ProcessRequestInternal(HttpResponse response, NameValueCollection queryString,
VirtualFileReader fileReader) at System.Web.Handlers.ScriptResourceHandler.ProcessRequest(HttpContext context) at
System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
i already tried wraping all inline javascript with //<![CDATA[ //]]>
i already set enableViewStateMac to false.
From looking at all the errors guessing out of the "d" paramter it seems to focus on a single usercontrol on my website.
in this control i change the visiblity of div's + text in the usercontrol OnPreRender function.
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
PreparePage();
}
Can the errors be related to the usercontrol behavioral?
thanks!

If your site is running in a web farm this might be related to having different machine keys. For example if one server is used to encode the viewstate then another server won't be able to decode it if it does not have the same machine key. Checkout this article. Even if you don't have multiple servers try specifying fixed machine keys.

The invalid ViewState exception is generally from ASP.NET's built in event validation. Turning off EnableViewStateMac simply stops the MAC-based encryption, not the viewstate validation. To do that you need to set EnableEventValidation="false" in the Page directive.
As to why it's happening... three possible reasons:
1) You are modifying the contents of a control on the client side (such as DropDownList items).
2) The page is being posted back before the ViewState validation field is being rendered.
3) Your site is the target of a malicious script searching for vulnerabilities... in which case, EventValidation is doing its job.
I'd say #1 is most likely... bu #2 is also very common, especially when you're seeing this error inconsistently.

Related

Viewstate exception Validation of viewstate MAC failed

In our log files I find the following exception. (ASP.NET, Sitecore 6.6). Any ideas why this happens?
I referred to this post. My app is not in a server farm. Also this does not happen with every postback.
7776 02:11:53 ERROR Application error.
Exception: System.Web.HttpException
Message: 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.
Source: System.Web
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.Web.UI.ViewStateException
Message: Invalid viewstate.
Client IP: xxx.xxx.xxx.201
Port: <PORT>
Referer: <URL>
Path: /<PAGE>
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
ViewState: /wEPDwUJMzY0OTY5Mjg5D2QWAgIFEGRkFgQCAw9kFgJmD2QWAmYPZBYCAg4PZBYCZg9kFgQCAw8PFgQeFUN1cnJlbnRTZWxlY3Rpb25WYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHhRDdXJyZW50U2VsZWN0aW9uVGV4dAUVQWxsIENhdGVnb3JpZXMgKDY5NTEpZBYCAgEPZBYCZg9kFgICAQ8UKwACDxYGHgRUZXh0BRVBbGwgQ2F0ZWdvcmllcyAoNjk1MSkeBF8hU0ICAh4IQ3NzQ2xhc3MFB1Rvb2xCYXJkEBYBZhYBFCsAAmRkDxYBZhYBBXdUZWxlcmlrLldlYi5VSS5SYWRDb21ib0JveEl0ZW0sIFRlbGVyaWsuV2ViLlVJLCBWZXJzaW9uPTIwMTIuMi42MDcuMzUsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49MTIxZmFlNzgxNjViYTNkNBYCAgIPFCsAAWQWAgIBDxQrAAIUKwACFCsAAg8WBB8EBQdUb29sQmFyHwMCAmQPFCsAARQrAAIPFgYfAgUVQWxsIENhdGVnb3JpZXMgKDY5NTEpHgVWYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHghTZWxlY3RlZGdkZA8UKwEBZhYBBXNUZWxlcmlrLldlYi5VSS5S...
please check this link
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.
And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
Workarounds
1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:
This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.
I have similar issue in my recent project.When I tried to find some help from google, the things that most people discussed are the following
Add machine key in web.config
<system.web>
<machineKey validationKey="..." decryptionKey="..." validation="SHA1" />
</system.web>
Set EnableViewStateMAC=False in web.config
<system.web>
<pages enableViewStateMac="False"/>
</system.web>
But all above solution did not work for me. Whenever I try to open application with IP address it works fine but if I tried open application with domain name it showed me "Viewstate MAC failed" error. I dig down to find out what an issue and finally I found solution, this error occurs when browser does not accept cookie from server.
Godaddy provides feature for domain forwarding with masking. One of my colleague set that feature on our application domain, IE and Safari have security Level that they does not accept cookies from third parties and Advertiser, therefore both these browser generated "Viewstate MAC failed" error.
You can set Security Level to Accept all cookie in IE
Tools > Internet Options > Privacy
and Move Setting slider bottom for the Value "Accept all Cookie".
Hope this solution will help other to get out of asp.net legacy error "Viewstate MAC failed".

CSHTML rendering text only - static page?

This is a continuation of my previous question (.CSHTML pages will not render), but I am no longer getting a 500 error, thus the new post. My pages are now just rendering plain text / html (regardless of what I do).
I can get the pages to work correctly if I try to view them through WebMatrix3, but I cannot view them from the browser (either localhost or through the web).
I recently realized that my pages were set up for ASP.NET v2.0, which I am guessing does not support .cshtml. So, I changed everything to v4.0 but I still don't have any luck view the pages correctly. It's just plain text.
I have:
MVC 3 installed
IIS 7.5 on Win7 Home Premium
The dir of the pages that I want to load converted to application
web.config functioning, though I am not sure what else, if anything I need to have it in
My server functioning normally with HTML, .css, .php, python, etc... But I am having horrible luck with any ASP.NET functionality (this includes .aspx).
I really don't know what other information I need to put here, but if you ask for it, I shall provide it.
EDIT 1:
Now I am just getting 404 errors on any .cshtml page I try to view. This happened before when I didn't have the MIME types in, but was corrected (to at least plain text) when I entered the MIME type in. I have no idea what is going on... at this point I am almost ready to just uninstall everything and try to start over. =\
EDIT 2:
Okay, so I have gotten rid of my 404 and 500 errors. I ended up adding a privileged user to the application pool (advanced settings > process model > Identity). It was set as defaultAppPool before. Now I am getting this:
Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Type 'ASP._Page_default2_cshtml' does not inherit from 'System.Web.WebPages.WebPage'.]
System.Web.UI.Util.CheckAssignableType(Type baseType, Type type) +9633480
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +66
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(String virtualPath, Type requiredBaseType) +28
System.Web.WebPages.BuildManagerWrapper.CreateInstanceOfType(String virtualPath) +203
System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +145
System.Web.WebPages.VirtualPathFactoryManager.CreateInstanceOfType(String virtualPath) +153
System.Web.WebPages.VirtualPathFactoryExtensions.CreateInstance(IVirtualPathFactory factory, String virtualPath) +73
System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(String virtualPath, IVirtualPathFactory virtualPathFactory) +23
System.Web.WebPages.WebPageRoute.DoPostResolveRequestCache(HttpContextBase context) +349
System.Web.WebPages.WebPageHttpModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +89
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Any more ideas? Oh, and creating a new application didn't help, but it was a good idea.
It could be that an older version of System.Web.WebPages.dll is loaded to memory, and it tries to cast the your cshtml page to a version of WebPages class from that dll.
To test this, try to see what http modules are currently registered:
var allModules = HttpContext.Current.ApplicationInstance.Modules;
for( int i = 0; i < allModules.Count; i++ ) {
Trace(allModules.GetKey(i));
}
In my case that was:
....
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_bca8e05a-5746-45b0-be95-2b920b455ccf
__DynamicModule_System.Web.WebPages.WebPageHttpModule, System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35_c1a67b42-31a9-47f1-8483-9e712fabe2a7
To fix the problem you need to replace the older version of System.Web.WebPages.dll in your /Bin folders, or some other dlls that might be referencing it.
You can try explicitly setting the ContentType in the action:
public ActionResult NotFound() {
Response.ContentType = "text/html";
return View(); }

asp.net error: This is an invalid webresource request

I am getting a ton of error alerts from one of my asp servers in a web farm, and all the servers have the same machine key in their web.config files.
I've looked around here but didn't find this exact case answered. Any suggestions would be welcome.
thanks for considering the question!
Here are some of the the error stacks (the query string is not from our app and could be part of something else):
Error message: This is an invalid
webresource request. Stack trace:
at
System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext
context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
Source: System.Web Method: Void
System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext)
Page: QueryString: d=hAGTq1Iohid
These may have started when the Win 2003 server was patched. Later dot.net frameworks were installed on three other servers but not on the one throwing the errors.
Most of the error seem related to decryption but all servers in the same web farm now same machine key in their web config. But that has not stopped the errors.
Seeing as well :
"Length of the data to decrypt is invalid"
Error message: Length of the data to decrypt is invalid. Stack trace: at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo) at System.Web.UI.Page.DecryptString(String s) at
System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessReques­t(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.I­ExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
And Also
"Invalid length for a Base-64 char array"
Error message: Invalid length for a Base-64 char array.
Stack trace: at System.Convert.FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length)
at System.Web.HttpServerUtility.UrlTokenDecode(String input)
at System.Web.UI.Page.DecryptString(String s)
at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Source: mscorlib
Method: Byte[] FromBase64CharArray(Char[], Int32, Int32)
And
"Invalid view state"
Error message: Invalid viewstate.
Stack trace: at System.Web.UI.Page.DecryptString(String s)
at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Source: System.Web
Method: System.String DecryptString(System.String)
Thanks again everyone.
I can't be sure, but it looks like a hack attempt trying to exploit the very serious .NET 'Padding Oracle' Crypto Attack, also discussed by Scott Guthrie. There is a patch available, so if you find that your server is indeed vulnerable, make sure you patch it immediately, and take damage-control steps if it has in fact been compromised.
This could also be caused by a problem with your application. However, if you're suddenly seeing large amounts of these errors, especially without any recent changes to your app, my first thought would be an intrusion attempt. The method used to exploit this vulnerability would generate errors related to decryption and bad data length.
If this server is the only one that is both unpatched AND showing the errors then the very first thing I would do is run all the windows updates on it.
Actually, let me make that statement less complicated: If this server is unpatched, start there and apply them.
UPDATE
You mentioned that the servers are throwing viewstate length errors. One thing we found was that several components, notably data grids, shove a tremendous amount of data into viewstate. Another thing was that several browsers would choke on this depending on length and not send all of it back.
After we made a particular web.config change this problem went completely away. Even Safari 3 started working right. Go to the <system.web> <pages /> node and make the following change:
<pages maxPageStateFieldLength="500" />
This will cause viewstate to be broken up across multiple hidden fields at 500 bytes each. It's an automatic split so none of your regular code has to change to support it.
You might play with the value, but essentialy some browsers can only send so much data back per input field. Depending on the version I've seen safari choke when those values were much more than around 700 bytes or so. Also firewalls and proxy servers might cause issues as well. See the following for a bit more information: http://weblogs.asp.net/lduveau/archive/2007/04/17/viewstate-chunking-in-asp-net-2-0-maxpagestatefieldlength.aspx
Another option to pursue is to have viewstate cached locally and not send it across the wire at all. Of course, that has implications in a web farm scenario so pick your poison.
Happened to me just now on a web site, for no apparent reason: The request for a web resource generated "invalid request" error and all the scripts were broken.
Could be an update to the server, maybe..
My solution was to go to the IIS control panel and to generate a new machine key for the site.
This seems to solve the problem, whatever that was.

Handle URI hacking gracefully in ASP.NET

I've written an application that handles most exceptions gracefully, with the page's design intact and a pretty error message. My application catches them all in the Page_Error event and there adds the exception to HttpContext.Curent.Context.Items and then does a Server.Transfer to an Error.aspx page. I find this to be the only viable solution in ASP.NET as there seems to be no other way to do it in a centralized and generic manner.
I also handle the Application_Error and there I do some inspection on the exception that occurred to find out if I can handle it gracefully or not. Exceptions I've found I can handle gracefully are such that are thrown after someone hacking the URI to contain characters the .NET framework considers dangerous or basically just illegal at the file system level.
Such URIs can look like e.g.:
http://exmample.com/"illegal"
http://example.com/illegal"/
http://example.com/illegal /
(notice the space before the slash at the end of the last URI).
I'd like these URIs to respond with a "404 Not Found" and a friendly message as well as not causing any error report to be sent to avoid DDOS attack vectors and such. I have, however, not found an elegant way to catch these types of errors. What I do now is inspect the exception.TargetSite.Name property, and if it's equal to CheckInvalidPathChars, ValidatePath or CheckSuspiciousPhysicalPath, I consider it a "path validation exception" and respond with a 404.
This seems like a hack, though. First, the list of method names is probably not complete in any way and second, there's the possibility that these method names gets replaced or renamed down the line which will cause my code to break.
Does anyone have an idea how I can handle this less hard-coded and much more future-proof way?
PS: I'm using System.Web.Routing in my application to have clean and sensible URIs, if that is of any importance to any given solution.
It may be that System.Web.Routing supports some sort of url filtering, but it is quite easy to implement your own.
Look at the System.Web.IHttpModule interface and read about implementing custom HTTP Modules. Http modules enter that Asp.Net pipeline and run before your page is run. You can use it to perform logging of requests, to modify requests and in your case to filter requests. The Asp.Net routing module is also implemented as a custom HTTP Module.
What you can do is to implement a Http Module that looks at the requested url and check if it is valid. If the url is invalid you can do whatever you need, for example redirect it to your 404 - not found page or you can just stop the request.
I don't think using System.Web.IHttpModule is the correct answer for IIS7+. I am trying to implement IHttpModule to validate the path but the exception has been thrown before the HttpModule is executed.
This is my exception stack:
[ArgumentException: Illegal characters in path.]
System.IO.Path.CheckInvalidPathChars(String path) +7493413
System.IO.Path.Combine(String path1, String path2) +40
System.Web.Configuration.UserMapPath.GetPhysicalPathForPath(String path, VirtualDirectoryMapping mapping) +114
System.Web.Configuration.UserMapPath.GetPathConfigFilename(String siteID, VirtualPath path, String& directory, String& baseName) +72
System.Web.Configuration.UserMapPath.MapPath(String siteID, VirtualPath path) +30
System.Web.Configuration.UserMapPath.MapPath(String siteID, String path) +31
System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull) +297
System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath, Boolean permitNull) +51
System.Web.CachedPathData.GetConfigPathData(String configPath) +341
System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) +110
System.Web.HttpContext.GetFilePathData() +36
System.Web.HttpContext.GetConfigurationPathData() +26
System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context) +43
System.Web.Configuration.CustomErrorsSection.GetSettings(HttpContext context, Boolean canThrow) +41
System.Web.HttpResponse.ReportRuntimeError(Exception e, Boolean canThrow, Boolean localExecute) +101
System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +383
and this is the link to Application Life Cycle for IIS 7.0 (http://msdn.microsoft.com/en-us/library/bb470252.aspx)
I am guessing that the exception caused by the "RESOLVE CACHE" step
Writing Custom HttpModule didn't work for me - I still got the "Illegal characters in path" error, but answer to this question solved the problem:
Turns out you could avoid this by setting allowDoubleEscaping="false" in for requestFiltering in web.Config. I.e:
<configuration>
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="false" />
</security>
</system.webServer>
</configuration>
Perhaps not the perfect solution (any suggestions for a better one is much appreciated), but it solves the problem.

Strange unhandled exception from asp.net application - Validation of viewstate MAC failed

I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing.
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. AutoGenerate
cannot be used in a cluster.
Stack Trace: at
System.Web.UI.ViewStateException.ThrowError(Exception
inner, String persistedState, String
errorPageMessage, Boolean
macValidationError) at
System.Web.UI.ObjectStateFormatter.Deserialize(String
inputString) at
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
serializedState) at
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter
formatter, String serializedState) at
System.Web.UI.HiddenFieldPageStatePersister.Load()
at
System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest()
at
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context) at
System.Web.UI.Page.ProcessRequest(HttpContext
context) at
ASP.generic_aspx.ProcessRequest(HttpContext
context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
Source: System.Web
Anybody have any ideas on how I could resolve this? Thanks.
I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.
If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered
form tag, you'll see something like this:
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" />
When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing.
The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click.
One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered?
from http://forums.asp.net/p/955145/1173230.aspx
#Chris
if the problem is clicking an item before the page has completely rendered, asp.net 3.5 SP1 added a web.config entry on the page element called renderAllHiddenFieldsAtTopOfForm.
do you have multiple servers running this application and/or have a web garden? If yes, you are going to have to set the machine key in the web.config
By default, ASP.NET includes a digital signature of the ViewState value in the page. It does so with an automatically-generated key that is held in memory. This is done to prevent a malicious user from altering the ViewState from the browser and, for example, grant him/herself access to stuff they wouldn't normally have access to.
ASP.NET can also, optionally, encrypt the ViewState, but it's turned off by default for performance reasons. In many web sites, it is a lot more important to make sure that the content of the ViewState is not 'mucked with', than it is to keep it confidential.
The error message says that the signature verification failed. The page was posted with a ViewState, but the ViewState signature didn't match the signature calculated with the keys held by the server.
The most common reason for this error is that you are using two or more web servers in a farm-like environment: one server sends the original page, signed with the key in memory on that server, but the page is posted back to the second (or third...) server. Because the two or more servers don't share the signature key, the signatures don't match.
...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.
What the error message is telling you is to use the validationKey attribute (see details in MSDN) in your web.config to hardcode the signature key to a value shared by all your servers, instead of using a dynamically-generated one. That way, the signature validation can succeed independently of which server receives the postback.
You could turn off the verification, but it's very dangerous to do so. It means any hacker with a bit of free time can fake values in your application. For example, if you keep the price of the item in a ViewState value, the hacker could change the value from the browser to $0.01 right before putting the order.
For anyone else ending up struggling with this issue here is a helpful link to some work arounds:
http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
I know you can disable the Validation of viewstate MAC, but I think if the page is not loaded you can get into more trouble. When I ran into this problem I had to disable all buttons until the page was fully loaded.

Resources