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)
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:
Invalid Webresource.axd parameters being generated
IE 8 dropping memory pages?
http://forums.asp.net/t/1373410.aspx?PageIndex=1
http://forums.asp.net/p/1409964/3085329.aspx
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
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?
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.
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!
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.
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.
If your viewstate looks bloated,
turn on GZip compression on in IIS.
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
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.
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].
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?
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..
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
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.
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.
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" />
Related
I am trying to troubleshoot an issue that is only happening in Internet Explorer on a production server. In my Visual Studio dev environment everything works fine. On production in any browser but IE everything works fine.
It is happening during the page load of a specific page in my application. After the page load, all subsequent postbacks do not work. I get a 408 error in Fiddler.
I found this post and it must be exactly what my problem is because as soon as I added the suggested meta tags to my master page everything works fine.
<meta http-equiv="Cache-Control" content="no-store,no-cache,must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
Can someone give me a brief explanation of why these meta tags are needed for my site to work? I feel like something I am doing with the AJAX might be incorrect or my production IIS settings might be wrong. Or is it just IE being IE?
Which version of IE is installed, and are all patches installed?
Can you provide a network trace, or more information about the HTTP/408 in question? If Fiddler is generating the 408 as I suspect it is, the problem is related to the fact that the client promised to submit a POST body but then didn't send any bytes.
Historically, there have been a number of bugs in IE near here related to the fact that, if IE expects to get an NTLM/Negotiate authentication challenge on a request, it will deliberately omit the POST body (in violation of standards) to save bandwidth. If the server fails to send an Authentication challenge, the client then fails to submit the body and the request times out. http://blogs.msdn.com/b/ieinternals/archive/2010/11/22/internet-explorer-post-bodies-are-zero-bytes-in-length-when-authentication-challenges-are-expected.aspx
In IE10, there were additional bugs in this area that have since been fixed in patches.
As noted on the other question, this is down to session cookie handling by IE and IIS.
IIS requires that in order for a cookie-based login to remain valid, it should receive some sort of contact from the client within a certain time. Typically this might be 30 minutes.
If you tell IE that a resource at a URL is valid for an hour, or a day or forever, it may be more than 30 minutes before IE decides to re-check with the server to see if the page has changed. Instead it will used cached data.
Therefore, if you don't put appropriate cache times on your resources, and the user only looks at pages they have seen before, IE might not get in touch with the server (since it has all the data cached).
Therefore the login might timeout (408 error).
Probably the real underlying problem is you should set appropriate timeouts on your resources.
The headers/meta tags as given essentially turn off all caching - this is unnecessary and probably not what you want. If you are expecting the page to change every 5-10 minutes, you might want to put a cache timeout of 1 minute, for example. Instead consider how long IE should cache the resources for, and put that.
TL;DR: use proper cache-control headers.
I'm getting the error "HTTP Error 414. The request URL is too long." From the following article, I understand that this is due to a very long query string:
http://www.mytecbits.com/microsoft/iis/query-string-too-long
In web.config, I have maxQueryStringLength="2097151". Is this the maximum value?
In order to solve this problem, should I set maxUrl in web.config? If so, what's the maximum value supported?
What should I do to fix this error?
This error is actually thrown from http.sys, not from IIS. The error gets thrown before the request is passed along to IIS in the request-handling pipeline.
To verify this, you can check the Server header value in the HTTP response headers, as per https://stackoverflow.com/a/32022511/12484.
To get https.sys to accept longer request URLs without throwing the HTTP 414 error, in the Windows Registry on the server PC, at Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters, create a DWORD-type value with name MaxFieldLength and value sufficiently large, e.g. 65535.
Reference: Http.sys registry settings for Windows
If you decide to make this change, then obviously it’ll need to be made in all environments (including all production server(s)) -- not just on your local dev PC.
Also, whatever script and/or documentation your team uses to set up new server instances will need to be updated to include this registry setting, so that your team doesn’t forget to apply this setting 18 months from now when setting up a new production server.
Finally, be aware making this change could have adverse security consequences for all applications running on your server, as a large HTTP request submitted by an attacker won’t be rejected early in the pipeline as it would normally.
As an alternative to making this change to bypass the http.sys security, consider changing the request to accept HTTP POST instead of HTTP GET, and put the parameters into the POST request body instead of into a long URL. For more discussion on this, see question Design RESTful GET API with a long list of query parameters.
As described in this answer -> What is the maximum length of a URL in different browsers?
The allowed length of a url depends on a combination of browser and server. Hence it's hard to say exactly how long the url can be. The answer recommends to stay below 2000 char in the url. I do not know why your querystring is so long. Can you shorten it? It's hard to give you any recommendations without knowing more about the solution and your query string.
Generally, Url has its own limits in length and if you set this value you may solve the problem for a while, but bear in mind that for a long url situations, best practice is working with forms. To be specific, it is better to use POST actions instead of Get.
just to complement, if you try with massive parameters, using Request ajax and receive de 414 ERROR. change the dataType property to JSON then submit as POST type.
this resolved my problem.
I get the following exceptions every couple of days:
System.Web.HttpException (0x80004005): 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. ---> System.Web.UI.ViewStateException: Invalid viewstate.
The thing is that I have a machine key set, and I also use only a single server (ie no cluster). So why is this exception happening? The only thing I can think of is that I keep reseting the IIS server, but I can't quite work out why that's a problem. Do you guys see this exception on a regular basis?
For reference, the following exists under my 'system.web':
<machineKey validationKey="Blah1" decryptionKey="Blah2" validation="SHA1" decryption="AES" />
To elaborate a little on Brian's point, the reason pages which are 'pretty large' experience problems is that those pages are sometimes rendered so slowly that you press the 'submit' button before the ViewState has finished downloading, which causes it to appear corrupted and generates the error.
The only solutions to this are:
disable viewstate completely
use a script to only enable submit after the page is fully loaded
make sure ViewState is as near the top of the page as possible (which I think is bad for SEO if your site is public).
You could try and prove this were the case by seeing if there were any correlation between the speed pages were being loaded and the timing of the exception. Using a tool like LogParser could help with this.
I have created a custom wizard control that dynamically loads usercontrols as you progress though it. The wizard is behaving as expected in all environments (PC/MAC) and browsers I have tested however a client is reporting that she is unable to complete the wizard. What I know about the issue:
It always fails on the same wizard step for this user (not the first step)
When the user clicks on the 'next' button in the step, the controller reports that the request was not a postback request (ie. IsPostBack() == false) and displays the first page of the wizard
The client is using a Mac and is accessing the site using the latest version of Safari
If the client switches to Firefox, or even just switches the user agent in Safari to something other than Safari the problem goes away.
So the problem is that when the client reaches a certain step in the wizard and clicks 'next', instead of re-loading that step to initiate the save event, the controller is merely displaying the first step of the wizard.
The step that fails contains many different form controls including textboxes, dropdowns, checkboxes and a fileupload control. We thought that it might have something to do with invalid characters getting pasted in from Word or something similar but that seems strange seeing as the problem only appears to be happening in Safari.
No exceptions are thrown and the windows event log is not displaying any related errors/warnings.
What I am looking for is ways to diagnose this error. At the moment I've been unable to reproduce the behavior that the client is experiencing but after going on site and seeing it for myself I can verify that it is definitely a valid issue.
Update 26/10/2010:
We installed a proxy on the clients NIC in order to retrieve the requests and responses. Problem is that when running the proxy the client appears to not have to problem any more. Does this behavior make sense to anyone?
Update 27/10/2010:
After investigating the traffic on the clients machine we noticed that the response headers were including some entries related to a client side proxy and we confirmed that they are in fact running the squid proxy in their office. To rule out that it had anything to do with the problem we got them to turn if off and then try the wizard again. This time no problems were encountered! So the proxy seems to be interfering with the requests causing .NET to somehow record the POST request as a non-postback. The following lines were found in the response header of a failed request. Can anyone comment on how squid could cause the behavior we are experiencing and what we can do about it?
Via:1.0 squid-12 (squid/3.1.0.13), 1.0 ClientSiteProxy:3128 (squid/2.7.STABLE4)
X-Cache:MISS from squid-12, MISS from ClientSiteProxy
X-Cache-Lookup:MISS from ClientSiteProxy:3128
If I have to troubleshoot this, I would first take a fiddler trace (www.fiddlertool.com) on the client and see what the requests are up to. I am not sure if Fiddler works on Mac, but any HTTP Watch, Network Monitor tool should be good. The reason that I am not doubting the code is that it works very well on all the other browsers, so the code shouldn't be bad.
May be there is something in the code [like adding cookies, etc] that is messing with the specific Client's browser.
HTH,
Rahul
For Mac There's a HTTPScoop which lets you to debug http post data's....it is similar to fiddler
The problem is not solved as such but we ended up just adding an exception to the clients squid proxy to bypass our website. The problem seems proxy/IIS/Safari related but we haven't been able to track the problem down any further and the client is happy with this solution as long as the problem doesn't resurface somewhere else. I'll re-post if more information surfaces.
OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own URL Rewriting module. Would this help solve our problem?
Thanks.
Microsoft released a hotfix for this :
http://support.microsoft.com/default.aspx/kb/956578
Since IIS7 uses .net from the top down there would not be any performance overhead of using an HttpModule, In fact there are several Managed HttpModules that are always used on every request. When the BeginRequest event is fired, the SessionStateModule may not have been added to the Modules collection, so if you try to handle the request during this event no session state info will be available. Setting the HttpContext.Handler property will initialize the session state if the requested handler needs it, so you can just set the handler to your fancy 404 page that implements IRequiresSessionState. The code below should do the trick, though you may need to write a different implementation for the IsMissing() method:
using System.Web;
using System.Web.UI;
class Smart404Module : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.BeginRequest += new System.EventHandler(DoMapping);
}
void DoMapping(object sender, System.EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (IsMissing(app.Context))
app.Context.Handler = PageParser.GetCompiledPageInstance(
"~/404.aspx", app.Request.MapPath("~/404.aspx"), app.Context);
}
bool IsMissing(HttpContext context)
{
string path = context.Request.MapPath(context.Request.Url.AbsolutePath);
if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path)
&& System.IO.File.Exists(System.IO.Path.Combine(path, "default.aspx"))))
return true;
return false;
}
}
Edit: I added an implementation of IsMissing()
Note: On IIS7, The session state module does not run globally by default. There are two options: Enable the session state module for all requests (see my comment above regarding running managed modules for all request types), or you could use reflection to access internal members inside System.Web.dll.
The problem in IIS 7 of post variables not being passed through to custom error handlers is fixed in service pack 2 for Vista. Haven't tried it on Windows Server but I'm sure it will be fixed there too.
Just a guess: the handler specified in IIS7's %windir%\system32\inetsrv\config\applicationhost.config which is handling your request is not allowing the POST verb to get through at all, and it is evaluating that rule before determining whether the URL doesn't exist.
Yes, I would definitely recommend URL rewriting (using Microsoft's IIS7 one or one of the many alternatives). This is specifically designed for providing friendly URLs, whereas error documents are a last-ditch backstop for failures, which tends to munge the incoming data so it may not be what you expect.