Invalid Viewstate error and how to fix it?

Discussion in 'ASP.NET 2.0' started by Bruce, Mar 10, 2006.

  1. Bruce

    Bruce DiscountASP.NET Staff

    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='2EEA416CEFC6D6BE856ED57B97FB9CA7DFACE17C073125949A1D682C80A44BB2A
    D887DDDC13DBFB0954F1000FEE5757E99693F222F8E28CAA2E6DAB8C4F99E0C'
    decryptionKey='877478B2F33A74226ABEF55FDCC1A76E43F1BBEA6241A592'
    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
     
  2. 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(String inputString)
    at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
    at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter 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(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
    at System.Web.UI.HiddenFieldPageStatePersister.Load()
    at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
    at System.Web.UI.Page.LoadAllState()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
    </font>
     
  3. Bruce

    Bruce DiscountASP.NET Staff

    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.
     
  4. 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
     
  5. Bruce

    Bruce DiscountASP.NET Staff

    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.
     
  6. 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
     
  7. 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.
     
  8. Bruce

    Bruce DiscountASP.NET Staff

    No. I don't think so. If user close their browser and hit the page again, it should have no viewstate information.
     
  9. 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 customer[​IMG]
    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\Temporary 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.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32&amp; dataLength) +289
    > System.Web.UI.ObjectStateFormatter.Deserialize(String 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: /wEPDwULLTE5MDUyNDM2MTUPZBYCAgQPZBYCAgEPPCsACgEADxYCHhJEZXN0aW5hdGlvblBhZ2VVcmwFF34vZW4vQWRtaW4vRGVmYXVsdC5hc3B4ZGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgIFEUxvZ2luMSRSZW1lbWJlck1lBRdMb2dpbjEkTG9naW5JbWFnZUJ1dHRvbpOUqZGopMeGEkI8Zt8AjNYsN7WM
    > 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(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
    > System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
    > System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
    > System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
    > System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
    > System.Web.UI.HiddenFieldPageStatePersister.Load() +207
    > System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +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(HttpContext 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\Temporary ASP.NET Files\root\90f2c220\7a829f89\App_Web_z7wwxzpp.3.cs:0
    > System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
    > System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
    > Boolean&amp; completedSynchronously) +75
    >
    >
    >
    >
    > ----------------------------------------------------------------------
    > ---------- Version Information: Microsoft .NET Framework
    > Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053
    </o:p>
     
  10. Bruce

    Bruce DiscountASP.NET Staff

    did you do what I suggested in the first post?
     
  11. 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!
     
  12. 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? in this forum.

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

    Thanks,
    Balu
     
  13. Does anyone think that getting tons of these errors would be received by search engines too, when they are crawling site?
     
  14. I had the same exact problem and this also solved it for me!
     
  15. elizas

    elizas Guest

    A Tip While Using ViewState

    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
     
  16. I have the same issue now with ASP.net 3.5. Does the solution(3) still work?

    Please recommend.
     
  17. A small gotcha

    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.

    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
     
  18. ...Nice, thanks for posting that. ;-)
     
  19. 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="88229FF53AE13DF382843079C45CABEE91CC97DCD0A780516C84026FE9939B42EEDD88AE81F05CF663D1EEF0C77DAAA888C9B42181FDDFDB2C1D17C0A297FBE4" decryptionKey="12D2245EC89F731BA61897653CD8851C49BC857DB3F37B69D6D790F5B9DE31AD" 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
     
  20. Invalid ViewState

    I encountered this error while moving from a page to another page
    <form action="page2.aspx">

    After doing research on the internet I could find that the issue is with the view state of the page1.aspx which was not validating against the machine key configuration of app.config file and so I disabled both the enableviewstates in the page tag like the one below in calling and called pages:
    <%@ Page Language="C#" EnableViewState="false" EnableViewStateMac="false"%>
    Hope this resolves yours also... best of luck
     
  21. martino

    martino DiscountASP.NET Staff

    Cool thanks for the added information guys.
     

Share This Page