PDA

View Full Version : Invalid Viewstate error and how to fix it?


bruce
03-10-2006, 08:16 AM
We have been getting some questions regarding viewstate-related errors like "The viewstate is invalid for this page and might be corrupted"

This error is usually caused by the asp worker process or the server recycling. By default, ASP.NET encrypts the viewstate using an Autogenerated Key when the process spins up. The problem comes when a client (browser) sends the request with a viewstate encrypted with the key generated by another worker process. Since the key is different, ASP.NET will not be able to decrypt the viewstate and it will throw the above error.

There are several ways to get around this problem:

1) Host your site on a server that never restarts or recycles!!! Obviously, this is impossible!

2) Disable ViewstateMac by putting this ?enableViewStateMac='false'? in your web.config. This approach is not 100% secure.

3) Configure ASP.NET to not use Auto-Generated Key but rather a predefined key. This is the preferred method.

To do this, follow these steps:

a) Either build your own Key Generator (http://support.microsoft.com/kb/313091/EN-US/) or use this tool (http://www.aspnetresources.com/tools/keycreator.aspx). I highly recommend you use the online tool. So assuming you will use the online tool:

b) In the online tool, simply click on ?Generate?.

c) Copy the content in the textbox into your site?s web.config file. The machineKey node should be within <system.web>

eg.

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<machineKey
validationKey='2EEA416CEFC6D6BE856ED57B97FB9CA7DFA CE17C073125949A1D682C80A44BB2A
D887DDDC13DBFB0954F1000FEE5757E99693F222F8E28CAA2E 6DAB8C4F99E0C'
decryptionKey='877478B2F33A74226ABEF55FDCC1A76E43F 1BBEA6241A592'
validation='SHA1' />
<compilation debug='false'/>
<authentication mode='Windows'/>
<pages enableViewStateMac='true'/>
</system.web>
</configuration>

For more information on viewstate troubleshooting, see http://support.microsoft.com/default.aspx?scid=kb;EN-US;829743

bdwest
04-26-2006, 02:55 AM
I am getting view state errors that says something like the following. Certain users generate the error more than others. I tried generating a machine key as described in the post from Bruce but it has no effect. The errors sound a little different because I never get a 'corrupt' view state message - just the Invalid viewstate. Any ideas as to what is wrong?

Thanks

Brian


---> System.FormatException: Invalid character in a Base-64 string.
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(Str ing inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.I StateFormatter.Deserialize(String serializedState)
at System.Web.UI.Util.DeserializeWithAssert(IStateFor matter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Web.UI.ViewStateException.ThrowError(Except ion inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMed ium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
</font>

bruce
04-26-2006, 06:35 AM
I dont' think my original post is related to this error. I think you may have something in your viewstate that asp.net doesn't like.

bdwest
04-26-2006, 08:47 AM
Bruce,

Any ideas as what asp.net may not like. I am absolutely clueless with this error. Luckily the user never sees the error. I trap for errors and they are emailed to me.

Thanks

Brian

bruce
04-27-2006, 06:04 AM
did more research, this may be caused by a viewstate hack bot.

There are some viewstate hack bots lurking out there that try to throw junk into an ASP.NET page in hope to use it to send spam.

The thing is, if you get this error, the bot failed.

bdwest
04-27-2006, 06:16 AM
Bruce,

Interesting - I have never heard of this before.

One final question and I will stop bugging you. This error is comming from a pages that have a complicated control a lot of view state information. I am using a Far Point spread control (fpoint.com). Could a user cause this error by exiting the browser or hitting the stop button during the time the view state information was being transferred back to the client? Or maybe their connection is tempermental and the transfer is interrupted momentarily.


Again

Thanks

joelnet
04-27-2006, 10:50 AM
I had some errors like this on a few pages, I was too lazy to figure out the cause... so i just disabled viewstate validation.

bruce
04-28-2006, 01:57 AM
Could a user cause this error by exiting the browser or hitting the stop button during the time the view state information was being transferred back to the client? Or maybe their connection is tempermental and the transfer is interrupted momentarily.No. I don't think so. If user close their browser and hit the page again, it should have no viewstate information.

thinksomid
10-17-2008, 09:23 AM
hi dear support
i have this error on some weak web hostings and im very glad that just one
time i had same error ondiscountasp web server .
it saved me against of my customerhttp://community.discountasp.net/emoticons/turn.gif
like bdwest,i have many usercontrols with complecated viewstates.
could you help me please?
best regards


> Server Error in '/' Application.
> ----------------------------------------------------------------------
> ----------
>
> 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.
> 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: 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 Error:
>
>
> [No relevant source lines]
>
>
> Source File: c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temp orary ASP.NET Files\root\90f2c220\7a829f89\App_Web_z7wwxzpp.3.cs Line: 0
>
> Stack Trace:
>
>
> [HttpException (0x80004005): Unable to validate data.]
> System.Web.Configuration.MachineKeySection.GetDeco dedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32&amp; dataLength) +289
> System.Web.UI.ObjectStateFormatter.Deserialize(Str ing inputString)
> +140
>
> [ViewStateException: Invalid viewstate.
> Client IP: 83.147.198.115
> Port: 1421
> User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)
> ViewState: /wEPDwULLTE5MDUyNDM2MTUPZBYCAgQPZBYCAgEPPCsACgEADxY CHhJEZXN0aW5hdGlvblBhZ2VVcmwFF34vZW4vQWRtaW4vRGVmY XVsdC5hc3B4ZGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmF ja0tleV9fFgIFEUxvZ2luMSRSZW1lbWJlck1lBRdMb2dpbjEkT G9naW5JbWFnZUJ1dHRvbpOUqZGopMeGEkI8Zt8AjNYsN7WM
> Referer: http://www.iretow.com/login.aspx?ReturnUrl=%2fen%2fAdmin%2fDefault.aspx% 3fpage%3dMenus&amp;page=Menus
> Path: /login.aspx]
>
> [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.ThrowError(Except ion inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
> System.Web.UI.ViewStateException.ThrowMacValidatio nError(Exception inner, String persistedState) +14
> System.Web.UI.ObjectStateFormatter.Deserialize(Str ing inputString) +242
> System.Web.UI.ObjectStateFormatter.System.Web.UI.I StateFormatter.Deserialize(String serializedState) +4
> System.Web.UI.Util.DeserializeWithAssert(IStateFor matter formatter, String serializedState) +37
> System.Web.UI.HiddenFieldPageStatePersister.Load() +207
> System.Web.UI.Page.LoadPageStateFromPersistenceMed ium() +105
> System.Web.UI.Page.LoadAllState() +43
> System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785
> System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242
> System.Web.UI.Page.ProcessRequest() +80
> System.Web.UI.Page.ProcessRequestWithNoAssert(Http Context context) +21
> System.Web.UI.Page.ProcessRequest(HttpContext context) +49
> ASP.login_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temp orary ASP.NET Files\root\90f2c220\7a829f89\App_Web_z7wwxzpp.3.cs :0
> System.Web.CallHandlerExecutionStep.System.Web.Htt pApplication.IExecutionStep.Execute() +181
> System.Web.HttpApplication.ExecuteStep(IExecutionS tep step,
> Boolean&amp; completedSynchronously) +75
>
>
>
>
> ----------------------------------------------------------------------
> ---------- Version Information: Microsoft .NET Framework
> Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
</o:p>

bruce
10-17-2008, 11:44 AM
did you do what I suggested in the first post?

jdavidroberts
12-02-2008, 05:43 AM
Thank you for posting this. I was having problems with FormsAuthentication tickets getting dropped (after 30 minutes or so or cycling worker processes), and this was at the root of that. Shame on me for not looking here sooner!

balu_dotnet
02-24-2009, 07:43 AM
Hi i had the same issue with this attribute enableEventValidation="false"

Before we had .Net framework V1.1.4322, recently my admin installed V2.0 then we got this error
?Invalid postback or callback argument. </o:p>
Event validation is enabled using <pages enableEventValidation="true"/> in configuration or </o:p>
<%@ Page EnableEventValidation="true" %> in a page.

after i added attribute enableEventValidation="false" in web.config file, it is working fine.

but i had some issues with Javascript functions under postback in2.0 versions.

The javascript function which work under 1.1(under postback) is not working with 2.0

(Note: for more info. i already posted my qn keep in the value in textbox under postback (http://community.discountasp.net/default.aspx?f=24&amp;m=30307)? in this forum.

can any one help, i am strugling since 2 days.

Thanks,
Balu

buckeyejeff
03-04-2009, 01:06 PM
Does anyone think that getting tons of these errors would be received by search engines too, when they are crawling site?

THalladay
07-01-2009, 05:37 AM
Thank you for posting this. I was having problems with FormsAuthentication tickets getting dropped (after 30 minutes or so or cycling worker processes), and this was at the root of that. Shame on me for not looking here sooner!

I had the same exact problem and this also solved it for me!

elizas
01-24-2010, 10:40 PM
View state maintains data in a page across postbacks. And this data passes in form of hidden field data. There is a certain limitation of this hidden field. If your hidden field will be greater than that specified value, then sometimes firewalls and proxy servers refuse to let your data passes through. And in that case you have to disable your view state .This might cause many problem if you want your data to be passed.

So to overcome this problem you can do viewstate chunking. This is a process of splitting the data into multiple chunks and putting them into multiple hidden fields, So that there will not be any problem to your data to pass through. This chunking is done by adding "MaxPageStateFieldLength" property in the page tag in web.config file. The default value is -1 which indicates there is no maximum limit of data. You have to give the integer value which indicates the maximum bytes size for a viewstate field.

<pages maxPageStateFieldLength="20" >

...............................

</pages>



After verifying the amount of data you may prefer to do viewstate chunking.

Thanks,
Eliza

sivavt
10-25-2010, 04:51 AM
I have the same issue now with ASP.net 3.5. Does the solution(3) still work?

Please recommend.

PJ2010
12-03-2010, 01:00 PM
We have been getting some questions regarding viewstate-related errors like "The viewstate is invalid for this page and might be corrupted"


There are several ways to get around this problem:

3) Configure ASP.NET to not use Auto-Generated Key but rather a predefined key. This is the preferred method.



This is very true. I'll point out though that on rare occasions nothing works because of the way your program is written. This is mentioned in certain places on the web, including the Microsoft help topic on this subject, but one way I experienced it was when I wrote a program that was exponentially growing in Big-Oh (http://en.wikipedia.org/wiki/Big_O_notation). I solved the error by simply rewriting the algorithm! And a nice side benefit is that my app ran a lot faster too.



To do this, follow these steps:


c) Copy the content in the textbox into your site?s web.config file. The machineKey node should be within <system.web>

eg.

<configuration>

<pages enableViewStateMac='true'/>



I want to alert readers to a problem with adding the attribute <pages enableViewStateMac='true'/>in your web.config file that generated a warning from my compiler and a possible run-time error. Suppose you have in a ASP.NET page a directive such as <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebFormA.aspx.cs" Inherits="MYPROJECT.WebFormA" %> in one of your .aspx pages (I was using a Master page template on ASP 3.5 running under Visual Studio 2008)

It turns out this line is apparently redundant to the <pages ... attribute, because it is implicit by default that <%@ Page ... is equivalent to "enableViewStateMac='true'"! (by default, implicitly). So taking out <pages enableViewStateMac='true'/> from my web.config file solved this problem, and the program compiled without a warning.

Just a heads up. These type problems tend to be very specific to individual circumstances it seems, so your mileage may vary.

PJ

wisemx
12-04-2010, 04:29 AM
...Nice, thanks for posting that. ;-)

richof
10-19-2011, 08:03 AM
hello,

I'm deploying an MVC2 App and I'm having this problem.

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.


I already saw this thread:
http://community.discountasp.net/showthread.php?t=12941
http://community.discountasp.net/showthread.php?t=2719
http://community.discountasp.net/showthread.php?t=9605

I already tried all the solutions mentioned in this thread's but nothing resolves my problem.
Here is My web.config

<machineKey validationKey="88229FF53AE13DF382843079C45CABEE91CC97DCD0A780516C 84026FE9939B42EEDD88AE81F05CF663D1EEF0C77DAAA888C9 B42181FDDFDB2C1D17C0A297FBE4" decryptionKey="12D2245EC89F731BA61897653CD8851C49BC857DB3F37B69D6 D790F5B9DE31AD" validation="SHA1" decryption="AES" />

<pages validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" enableViewStateMac="true">

<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>


Could you help me please.
Thanks a Lot