C# .NET 应用程序中不稳定的无效视图状态问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/728513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:48:16  来源:igfitidea点击:

Erratic Invalid Viewstate issue in a .NET application

c#.netasp.netviewstate

提问by

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

我似乎时不时地在我的ASP.NET应用程序的事件查看器中收到“无效的视图状态” 。

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

他们中的大多数 (95%) 似乎都在引用ScriptResource.axd(应用程序使用ASP.NET AJAX库)。我无法删除Ajax库,因为 Ajax 无处不在。

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.

我怎样才能减少这些错误?我每天收到大约 100-200 个错误,我不知道如何修复它们!它们来自不同的浏览器、不同的 IP 和地理位置。

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.

我很难重现这个问题,因为它几乎没有发生在我身上,它只发生在我身上 3-4 次。

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:

我也时不时地在我的 .NET 代码中收到此错误,该错误同时发生,这可能是相关的:

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)

回答by eglasius

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].

使用机器密钥的自动配置时会出现此问题,每次回收应用域时都会获得一个新密钥。这会影响视图状态验证、动态资源查询字符串解密和身份验证票证 [插入机器密钥的其他用途]。

回答by Esteban Araya

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

当 Viewstate 太大时,我见过这样的问题。我已经看到它发生是因为 Freddy 描述的问题。

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

我通常不喜欢使用 Viewstate 的想法。你能完全关闭 Viewstate 吗?

回答by Daniel Liuzzi

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.

我猜你正在使用 ASP.NET AJAX。我有同样的问题。偶尔我会在我的事件日志中发现这个异常,并且请求的路径总是 ScriptResource.axd。

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

在 machineKey 中使用固定的验证密钥和解密密钥并没有解决我的问题。

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.

根据我所能收集到的信息,我倾向于认为这个错误与 ViewState 无关;我的理论是,出于某种原因,某些 UA 以某种方式弄乱了 ScriptResource.axd 的“d”参数。通过手动请求有问题的路径,这个问题很容易复制。这会产生“无效的 ViewState”异常,即使 ViewState 在这里不适用。

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

此请求服务正常 (200):/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NRCY1n0_DNg1nE6-DDbs9nlp3dpdw1dfcdbsdw1dfdzdfkdwwdffy3zd41w_33y_9dq6i10g

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

这个略有不同的请求也可以正常处理 (200):/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_33Y_9Dq6i10g9Q1NR5ijsxQts4AfbJdACRTLW1AfbJdACRTLW1AfbJdACRTLW1000C

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

此请求失败并返回 500 响应和 Invalid ViewState 异常:/ScriptResource.axd?d=oFCAB7_vUyp7Hhe9lxZBz37lpoAxhfbWwwdfFy3Zd3z41W_3 products$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.

如果仔细观察,所有三个请求的前几个字符是相同的,但最后一个请求的最后几个字符(粗体)显然是控件 ID“products$ctl00$AddToCart1$id”(我有一个名为 products 的控件和添加到购物车)。我不知道这个 ID 是如何到达那里的,但就我而言,这就是导致所有这些 Invalid ViewState 异常的原因。

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...

我不确定这是否与 OP 相同,但我注意到 Martin 的请求 URL 以“html”结尾,这对于一个应该是关键的参数来说有点巧合……

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

由于这个问题,我已经头疼了。到目前为止,我遇到的最有见地的帖子是这个http://bytes.com/topic/asp-net/answers/861764-invalid-viewstate-system-string-decryptstringwithiv

Any insights?

任何见解?

回答by Daniel Liuzzi

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.

我也遇到了这个问题,我已经尝试了我发现的所有博客中提到的所有内容(固定机器密钥、视图状态大小等)。99% 的错误记录在对 ScriptResource.axd 的请求中。我在 Win 2003 服务器上使用 .net 3.5 SP1。该应用程序托管在两台相同的并行服务器上,比例为 50/50。每个服务器都有相同的机器密钥。

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

通常这个错误我并不关心,但是,在 3 个月的时间里,发生的趋势一直在上升。

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..

有没有人认为这个错误与 Viewstate 没有被 UrlEncoded/HtmlEncoded 或 UrlDecoded 正确有关。也许视图状态中有一些字符子集,一些浏览器正在用一些编码值替换这些字符子集。我不确定这是否有意义..

回答by Sam

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.

由于某些原因,“NT Authority\Network Service”的帐户名称已被本地化为其他语言。
可悲的是,许多程序将帐户名硬编码为英文名称,并且在外国版本的 Windows 上运行时找不到网络服务,从而导致事件日志中出现各种奇怪的错误。

回答by JohnnyCantCode

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.

我刚刚为我将这个问题缩小到使用 Trend Micro 防病毒软件的用户,并且在他于 2009 年 5 月 21 日更新他的 Trend Micro 软件后,错误才开始发生。在此日期之前没有错误。

回答by Martin Clarke

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.

Viewstate 问题既烦人又令人沮丧 - 我注意到一些人在此线程中谈到了 Viewstate 问题。因此,这里有一些建议,您可以按顺序查看。

  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.

  1. 我会回应 Freddy Rios 已经在线程中所说的内容。确保您已对机器密钥进行硬编码。这将解决绝大多数这些问题。ScriptResource 链接的重要之处在于它应该在查询字符串中包含 ad 参数和 at 参数。如果没有其他问题!

  2. 在完成之前不要让用户回发。您可能可以使用 javascript 和一些 css 来做到这一点。根据记忆,我认为有一种方法可以使用元标记来做到这一点,但它可能仅适用于 IE。

  3. 我会看看是刷新响应早。我会认为脚本管理器之后最好。但您可能需要进行一些试验。

  4. 如果您的视图状态看起来很臃肿,请在 IIS 中打开 GZip 压缩。

  5. 如果您的视图状态变得非常臃肿并且您无法打开 GZip 压缩/或者它具有不希望的副作用。然后您可以压缩和解压缩视图状态。 http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx

  6. 如果这仍然给您留下臃肿的视图状态,您可以考虑将视图状态存储在本地。 http://blog.arctus.co.uk/articles/2007/04/23/advanced-asp-net-storing-viewstate-in-a-database/是一个很好的起点。

回答by Jim Petkus

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).

这似乎与许多人遇到的 IE8 问题相同。似乎发生的是,不知何故 IE8(在 IE8 渲染模式和 IE7 兼容模式下)将从 HTML 文档的中间丢失 4096 个字节,并且此丢失的数据导致此异常(您通常会在 ScriptResource 或 WebResource 调用中看到这一点) .

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

这是有关此问题的 Microsoft 错误报告: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.

注意是 Internet Explorer 8 中的一个错误。 Internet Explorer 团队一直在调查这个问题。

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.

影响:到目前为止,我们认为该问题对最终用户使用 Web 应用程序的体验没有影响;唯一的负面影响是 JavaScript 推测下载引擎发送的虚假/格式错误的请求。当解析器实际需要该脚本时,它会在那个时候被正确下载和使用。

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.

情况:虚假请求似乎仅在某些时间情况下发生,仅当包含带有 CHARSET 指令的 Content-Type 的 META HTTP-EQUIV 标记出现在文档中时,并且仅当 JavaScript SRC URL 跨越第 4096 个字节时HTTP 响应正文。

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.

解决方法:因此,我们目前认为可以通过使用 HTTP Content-Type 标头声明页面的 CHARSET 而不是在页面内指定它来缓解此问题。

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:

相反,在您的 head 标记中,发送以下 HTTP 响应标头:

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.

请注意,HTTP 标头中字符集的规范可提高所有浏览器的性能,因为浏览器的解析器在遇到字符集声明时无需从头重新开始解析。此外,使用 HTTP 标头有助于减轻某些 XSS 攻击向量。

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.

注意:有报告称,当 META HTTP-EQUIV 不在页面上时,此问题仍然会发生。当我们进行更多调查时,我们将更新此评论。

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

Microsoft 于 2009 年 6 月 30 日下午 12:25 发布。

Edit: I still see this exception occasionally, but this bug is reported as being fixed: http://blogs.msdn.com/b/ieinternals/archive/2010/04/01/ie8-lookahead-downloader-fixed.aspx

编辑:我仍然偶尔会看到这个异常,但这个错误被报告为已修复:http: //blogs.msdn.com/b/ieinternals/archive/2010/04/01/ie8-lookahead-downloader-fixed.aspx

回答by Sergio

I think, you must use in aspx page:

我认为,您必须在 aspx 页面中使用:

<!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

这解决了我的问题

回答by Jonathan

The problem seems to be the lookahead downloader in IE8.

问题似乎是 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.

它似乎只在相当模糊的情况下影响 IE8。它可能被忽视的原因之一是附加到 URL 的 4k 数据块经常被服务器丢弃。似乎使它更有可能发生的事情之一是网络连接缓慢。以下资源之一中的某人指出,他只与他在新西兰的客户有问题。

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

很多人解释了两个不同的问题,其中之一在上面的问题中有所描述(发送到服务器的格式错误的 URL):

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

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

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

KB980182– Cumulative update in which issue is fixed:

KB980182– 累积更新已修复问题:

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

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:

注意:因为如果前瞻下载器无法检索脚本会自动重新下载,所以应该可以改回旧的验证模式,在该模式中不检查 .axd 文件的有效性并消除问题:

<httpRuntime requestValidationMode="2.0" />