program story

.NET 응용 프로그램의 비정상적인 잘못된 Viewstate 문제

inputbox 2020. 12. 2. 21:03
반응형

.NET 응용 프로그램의 비정상적인 잘못된 Viewstate 문제


ASP.NET 응용 프로그램 의 이벤트 뷰어에서 가끔 "잘못된 뷰 상태"가 나타나는 것 같습니다 .

대부분 (95 %)은 참조하는 것으로 보입니다 ScriptResource.axd(응용 프로그램은 ASP.NET AJAX 라이브러리를 사용함 ). Ajax가 모든 곳에서 사용되기 때문에 Ajax 라이브러리를 제거 할 수있는 방법은 없습니다 .

이러한 오류를 어떻게 줄일 수 있습니까? 하루에 100 ~ 200 개의 오류가 발생하는데 어떻게 수정해야할지 모르겠습니다! 브라우저, IP 및 지리적 위치가 서로 다릅니다.

나에게도 거의 발생하지 않았기 때문에 문제를 재현하기가 어렵습니다. 갑자기 3-4 번만 발생했습니다.

오류:

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.

나는 또한 때때로 관련 될 수있는 동시에 발생하는 .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)

이것은 많은 사람들이 경험 한 것과 동일한 IE8 문제로 보입니다. 어떻게해서 든 IE8 (IE8 렌더링 모드 및 IE7 호환 모드 모두에서)은 HTML 문서 중간에서 4096 바이트를 잃고이 누락 된 데이터로 인해이 예외가 발생합니다 (일반적으로 ScriptResource 또는 WebResource 호출에서 볼 수 있음). .

문제에 대한 Microsoft 버그 보고서는 다음과 같습니다. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=434997

또한이 문제에 대한 많은 포럼, 블로그 등 게시물이 있습니다.


Microsoft는이 문제에 대응했습니다.

참고 사항은 Internet Explorer 8의 버그입니다. Internet Explorer 팀은이 문제를 조사하고 있습니다.

영향 : 지금까지 문제가 웹 애플리케이션에 대한 최종 사용자의 경험에 영향을 미치지 않는다고 생각합니다. 유일한 부정적인 영향은 자바 스크립트 추측 다운로드 엔진이 보낸 가짜 / 잘못된 요청입니다. 파서가 스크립트를 실제로 필요로 할 때, 그 때 적절하게 다운로드되어 사용됩니다.

상황 : 스퓨리어스 요청은 특정 타이밍 상황에서만 발생하는 것으로 보입니다. CHARSET 지시문이있는 Content-Type을 포함하는 META HTTP-EQUIV 태그가 문서에 나타날 때만, JavaScript SRC URL이 4096 번째 바이트에 걸쳐있는 경우에만 발생합니다. HTTP 응답 본문.

해결 방법 : 따라서 현재이 문제는 페이지 내에서 지정하는 대신 HTTP Content-Type 헤더를 사용하여 페이지의 CHARSET를 선언하여 완화 할 수 있다고 생각합니다.

그래서 넣는 것보다

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

대신 head 태그에서 다음 HTTP 응답 헤더를 보냅니다.

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

HTTP 헤더에서 문자 집합을 지정하면 모든 브라우저에서 성능이 향상됩니다. 브라우저의 파서가 문자 집합 선언을 만나면 처음부터 구문 분석을 다시 시작할 필요가 없기 때문입니다. 또한 HTTP 헤더를 사용하면 특정 XSS 공격 벡터를 완화하는 데 도움이됩니다.

참고 :이 문제는 META HTTP-EQUIV가 페이지에 없을 때 계속 발생한다는보고가 있습니다. 추가 조사가있을 때이 의견을 업데이트 할 예정입니다.

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


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.

  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.


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" />

참고URL : https://stackoverflow.com/questions/728513/erratic-invalid-viewstate-issue-in-a-net-application

반응형