63

I seem to be getting a "invalid viewstate" every now and then in the event viewer for my ASP.NET application.

Most of them (95%) seem to be referencing ScriptResource.axd (the application uses the ASP.NET AJAX library). There is no way I can remove the Ajax library either as Ajax is used everywhere..

How can I reduce these errors? I'm getting ~ 100-200 errors a day and I have no idea how to fix them! They come from different browsers, different IPs and geographical locations.

It's difficult for me to reproduce the problem because it barely even happened to me, it has only happened to me 3-4 times out of the blue.

Error:

Process information: 
    Process ID: 4004 
    Process name: w3wp.exe 
    Account name: NT AUTHORITY\NETWORK SERVICE 

Exception information: 
    Exception type: HttpException 
    Exception message: Invalid viewstate. 

Request information: 
    Request URL: http://domainnamehere/ScriptResource.axd?d=W1R6x9VzZ2C9SKnIkOmX9VRLhSjJ3nOF1GSQvPwKS3html 
    Request path: /ScriptResource.axd 
    User host address: 124.177.170.75 
    User:  
    Is authenticated: False 
    Authentication Type:  
    Thread account name: NT AUTHORITY\NETWORK SERVICE 

Thread information: 
    Thread ID: 1 
    Thread account name: NT AUTHORITY\NETWORK SERVICE 
    Is impersonating: False 
    Stack trace:    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)


Custom event details: 

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

I also get this error every now and then in my .NET code which happens at the same time which might be related:

Exception raised in GLOBAL.ASAX.Application_Error(): 'Padding is invalid and cannot be removed.' at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
   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, IVType ivType, Boolean useValidationSymAlgo)
   at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
splattne
  • 102,760
  • 52
  • 202
  • 249
  • I may be seeing crocodiles in your tea cup, but it may be a classic padding oracle attack executing against your web site. Before anything else, its always safe to encrypt whatever sensitive data in your web.config file before its too late. – Ε Г И І И О Oct 07 '12 at 08:02

10 Answers10

36

This appears to be the same IE8 issue that many people have been experiencing. What appears to happen is that somehow IE8 (in both IE8 rendering mode and IE7 compatibility mode) will lose 4096 bytes out of the middle of the HTML document and this missing data causes this exception (you usually see this in a ScriptResource or WebResource call).

Here is a Microsoft bug report on the issue: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=434997

Also there are plenty of forum, blog etc posts on this issue:


Microsoft has responded to this issue:

Note is a bug in Internet Explorer 8. The Internet Explorer team has been investigating this issue.

Impact: Thus far, we believe the problem has no impact on the end-user's experience with the web application; the only negative effect is the spurious/malformed requests sent by the JavaScript speculative-download engine. When the script is actually needed by the parser, it will properly be downloaded and used at that time.

Circumstances: The spurious-request appears to occur only in certain timing situations, only when a META HTTP-EQUIV tag containing a Content-Type with a CHARSET directive appears in the document, and only when a JavaScript SRC URL spans the 4096th byte of the HTTP response body.

Workaround: Hence, we currently believe this issue can be mitigated by declaring the CHARSET of the page using the HTTP Content-Type header rather than specifying it within the page.

So, rather than putting

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">

In your head tag, instead, send the following HTTP response header:

Content-Type: text/html; charset=utf-8

Note that specification of the charset in the HTTP header results in improved performance in all browsers, because the browser's parsers need not restart parsing from the beginning upon encountering the character set declaration. Furthermore, using the HTTP header helps mitigate certain XSS attack vectors.

NOTE: There have been reports that this problem still happens when the META HTTP-EQUIV is not on the page. We will update this comment when we have more investigation.

Posted by Microsoft on 6/30/2009 at 12:25 PM.

Edit: I still see this exception occasionally, but this bug is reported as being fixed: Link

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Jim Petkus
  • 4,500
  • 25
  • 19
4

I guess you are using ASP.NET AJAX. I am having the same problem. Sporadically I would find this exception in my Event Log, and the requested path is ALWAYS ScriptResource.axd.

Using fixed validationKey and decryptionKey in machineKey did not fix the problem for me.

Based on what I was able to gather, I tend to believe that this error has nothing to do with the ViewState whatsoever; my theory is that for some reason, certain UAs somehow mess up the "d" parameter of the ScriptResource.axd. The problem is easily replicable by requesting the offending path manually. This gives an "Invalid ViewState" exception, even though ViewState doesn't even apply here.

Digging through my logs, I found for example:

This request is served OK (200): /ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NRCY1n0_DNg1nE6-DDbsD6r4EiuwoeDzp9mjDDfBNLb1k1&t=41df03cc

This slightly different request is also served OK (200): /ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NR5ijsxQts4AfbJdACRwmQ8sHt6UAzui3spEnooPneTz01&t=41df03cc

This request fails with a 500 response and the Invalid ViewState exception: /ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_3products$ctl00$AddToCart1$id

If you look closely, the first few characters on all three request are the same, but the last few characters of the last request (in bold) clearly is Control ID "products$ctl00$AddToCart1$id" (I have a controls named products and AddToCart). I don't know how this ID got there, but in my case this is what is causing all these Invalid ViewState exceptions.

I'm not sure whether this is the same case as the OP or not, but I notice Martin's Request URL ends in "html", which is a bit of a coincidence for a parameter that is supposed to be a key...

I already have a headache thanks to this problem. And so far, the most insightful post I came across is this one http://bytes.com/topic/asp-net/answers/861764-invalid-viewstate-system-string-decryptstringwithiv

Any insights?

Daniel Liuzzi
  • 16,807
  • 8
  • 52
  • 57
  • yeh i did notice the strage chars in the request, i have no idea where they are coming from as well. i have seen that url but it didnt really help because all my scripts are in CDATA. –  Apr 09 '09 at 00:42
  • do you by any chance use any DevExpress or Telerik third party libraries? i do, and im thinking it might be related to this. –  Apr 09 '09 at 01:46
  • Nope. Not using DevExpress or Telerik. The only third party library I am using is jQuery, along with a couple plugins for it. The rest is just pure ASP.NET 3.5. – Daniel Liuzzi Apr 12 '09 at 08:28
  • do you by any chance have stylesheets that are autogenerated, ie. i noticed that i have some css like /WebResource.axd?d=YI1xEj-NpEfvWqTxv3dm9YM2b86Vydy2c3lTjeB4rymEZiO2KbU9ziGg3kuXZjW-rBHflB5c9AKVZDgisLcV6g2&t=633462802820000000 which has background urls with the same address. http://blogs.msdn.com/carloc/default.aspx?p=2 says that URLs to web resources should not be hardcoded but rather we must use GetWebResourceUrl instead but i dont know how to change those auto generated css files! :( –  Apr 20 '09 at 04:41
  • 7
    We have reproduced the problem here: downloaded a tool called Netlimiter. I limited my internet explorer to download speed of 1 KB. During a page request, I added a new url to my browser and navigated there (this would stop the current request and start a new one). I was able to generate the same error over and over again. The timing needs to be right though because I think you need to abort (or switch) the request at the exact point where either the viewstate or the scriptresources are loaded. So this means it happens with slow networks .. i suspect its a Bug with the .net Ajax library. –  Apr 29 '09 at 01:49
  • 1
    That is interesting. I will have to download netlimiter and try it out. I highly doubt that this is a .net bug however. This issue only occurs with an ie8 user agent string. I have noticed (as have others on the forums) that what is happening is that ie8 is chopping 4096 bytes out of the middle of the page. If you look at the querystring in your error you will probably notice some other portion of your page being plopped into the request for the webresource.axd. When I have investigated this portion of my page wa always 4096 characters after the last valid character in the request string. – Jim Petkus Jun 09 '09 at 14:45
4

Viewstate issues are annoying and frustrating - I've noticed a few people have talked about having Viewstate issues in this thread. So, here are some suggestions you can look at in order.

  1. I'd echo what Freddy Rios has said in the thread already. Make sure that you've hardcoded the machine key. This will solve the vast majority of these issues. The important thing about the ScriptResource link is that it should have a d parameter and a t parameter in the querystring. If it doesn't something else is wrong!

  2. Don't let the user postback until your done. You could probably do this with javascript and a bit of css. From memory, I think there is a way to do this with a meta tag but it might be IE only.

  3. I would look at is flushing the response early. I would think after the script manager would be best. But you might need to experiment a bit.

  4. If your viewstate looks bloated, turn on GZip compression on in IIS.

  5. If your viewstate has became really bloated and you can't get GZip compression turned on/or it has an undesired side affect. Then you can compress and uncompress the viewstate. http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx

  6. If that still leaves you with a bloated viewstate, you could look at storing the viewstate locally. http://blog.arctus.co.uk/articles/2007/04/23/advanced-asp-net-storing-viewstate-in-a-database/ is a good starting point.

Martin Clarke
  • 5,636
  • 7
  • 38
  • 58
1

I think, you must use in aspx page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

This solve my problem

Sergio
  • 11
  • 1
1

Use a fixed machine key (even when doing single server).

The issue occurs when using the auto configuration for the machine key, you get a new one each time the app domain is recycled. This affects viewstate validation, dynamic resources query string decryption and authentication tickets [insert other uses of the machine key].

eglasius
  • 35,831
  • 5
  • 65
  • 110
  • i tried this, and it didnt make a difference.. ie: added something like: –  Apr 08 '09 at 05:10
  • @Martin did you check it was working with a couple postbacks first? You mentioned you were having a hard time to repro, did something change? – eglasius Apr 08 '09 at 05:25
  • 1
    @Martin I assume you did, but just to be sure: remember you need to use keys with the appropriate size for each algorithm. – eglasius Apr 08 '09 at 05:27
  • no i didnt change anything, this error has always been around. What do you mean by use keys with the right size? I just used: http://www.developmentnow.com/articles/machinekey_generator.aspx –  Apr 08 '09 at 05:32
  • btw, its .net 3.5 with SP1 on windows server 2003 SP2 –  Apr 08 '09 at 05:33
  • @Martin the size of the keys was if you were using: http://msdn.microsoft.com/en-us/library/ms998288.aspx ... the code seems to be the same, the end result should be the same. After configuring it, browse the app and make sure it is working with the keys. – eglasius Apr 08 '09 at 05:42
  • also note you might get a some error entries for any postbacks occuring after doing the change, since you are changing the keys. Please let use know if you left it with the fixed keys and you are still getting the errors. – eglasius Apr 08 '09 at 05:44
  • i left it with the fixed keys (also tried restarting app pool) and still getting errors... :( left it for a day and still getting random errors in eventviewer –  Apr 08 '09 at 05:46
  • I do not think this is true I have always had a fixed machine key and receive these errors. – Element Aug 29 '09 at 16:10
1

I've seen problems like this when the Viewstate is too large. I've seen it happen becaue of the problem Freddy describes.

I generally dislike the idea of using Viewstate. Can you turn Viewstate off altogether?

Esteban Araya
  • 29,284
  • 24
  • 107
  • 141
  • I have tried to minimise viewstate and it hasnt made a difference .. :( i cant turn it off altogether because i would have to rewrite the whole application and that will take ages :( –  Apr 08 '09 at 05:09
1

I am also having this issue, and I've tried everything mentioned in all the blogs I've found (fixed machine key, viewstate size, etc). 99% of the time the error is logged on requests to ScriptResource.axd. I am using .net 3.5 SP1, on Win 2003 server. The app is hosted on two parallel identical servers, balanced 50/50. Each server has the same machine key.

Normally this error does not concern me much, however, over a 3 month period, the trend on occurance has been going way up.

Does anyone think this error is related to the Viewstate not being UrlEncoded/HtmlEncoded or UrlDecoded correctly. Perhaps there is character subset within the viewstate that some browsers are replacing with some encoded value. I'm not sure if that even makes sense..

  • 3
    We have reproduced the problem here: downloaded a tool called Netlimiter. I limited my internet explorer to download speed of 1 KB. During a page request, I added a new url to my browser and navigated there (this would stop the current request and start a new one). I was able to generate the same error over and over again. The timing needs to be right though because I think you need to abort (or switch) the request at the exact point where either the viewstate or the scriptresources are loaded. So this means it happens with slow networks .. i suspect its a Bug with the .net Ajax library. –  Apr 29 '09 at 01:47
0

The problem seems to be the lookahead downloader in IE8.

It seems to only affect IE8 in a fairly obscure set of circumstances. One of the reasons it can go unnoticed is that a 4k chunk of data appended to a URL is often discarded by the server. One of the things that seems to make it more likely is a slow network connection. Someone in one of the below resources noted that he only had the issue with his clients in New Zealand.

Lots of people explaining two separate problems, one of which is described in the question above (malformed URLs sent to server):

http://connect.microsoft.com/VisualStudio/feedback/details/434997/invalid-webresource-axd-parameters-being-generated

Article explaining that the lookahead downloader is fixed:

http://blogs.msdn.com/b/ieinternals/archive/2010/04/01/ie8-lookahead-downloader-fixed.aspx

KB980182 – Cumulative update in which issue is fixed:

http://support.microsoft.com/kb/980182

NOTE: Because the script is automatically re-downloaded if it couldn’t be retrieved by the lookahead downloader, it should be possible to change back to the old validation mode in which .axd files were not checked for validity and remove the symptoms of the issue:

<httpRuntime requestValidationMode="2.0" />
Jonathan
  • 25,873
  • 13
  • 66
  • 85
  • 1
    I got the same problem but it happens in IE8 and IE9, any ideas what can it be? – tif Mar 21 '12 at 14:20
0

Are you running a non-english Operation System?

For some reasons, the account name of "NT Authority\Network Service" has been localized in other languages.
Sadly, a lot of programs have the account name hard coded to the english name, and won't find the Network Service when running on foreign versions of Windows, leading to all kind of funky errors in the event log.

Sam
  • 28,421
  • 49
  • 167
  • 247
0

I have just narrowed this issue down for me to a user with Trend Micro antivirus and the errors just started to occur after he updated his trend micro software on 5/21/2009. No errors before this date.

JohnnyCantCode
  • 153
  • 1
  • 2
  • 6