Validation of viewstate MAC failed error


— 3/17/2009 UPDATE —

If you are using .NET 2.0 or later, please upgrade to .NET 3.5 SP1 (.NET 2.0 SP2) as it has a fix in it that should resolve this issue.  If you update and still have the problem, please post here so we know.

— 3/17/2009 UPDATE —

 

Issue Description

You can get this Exception:

 

HttpException (0x80004005): Validation of viewstate 
MAC failed. If this application is hosted by a Web 
Farm or cluster, ensure that  configuration 
specifies the same validationKey and validation 
algorithm. AutoGenerate cannot be used in a cluster.

 

when the following preconditions are true:

1. You aren’t using a web farm.

2. It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.

3. It appears if you have a large page which loads slowly for any reason.

If following preconditions are true and you click a postbacking control/link and the page hasn’t loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.

When this happens, if you just try setting the page property "EnableViewStateMac" to false, it does not solve the problem, it just changes the error message in same navigation behavior:

 

The state information is invalid for 
this page and might be corrupted.

 

Other exceptions that seem to be the same problem look like:

Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.test_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec
utionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 
completedSynchronously) 

Nested Exception 

Exception: System.ArgumentException
Message: Invalid postback or callback argument. 
Event validation is enabled using in configuration
or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback
events originate from the server control that
originally rendered them. If the data is valid
and expected, use the
ClientScriptManager.RegisterForEventValidation
method in order to register the postback or
callback data for validation. Source: System.Web at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(St ring postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

and

Content-Length:1232
Content-Type:application/x-www-form-urlencoded
Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-us
Cookie:ASP.NET_SessionId=skk4vriy1lzghm55bicesz45; 
Host:
User-Agent:T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; 
Smartphone; 320x240) UA-OS:Windows CE (Smartphone) - Version 5.1
UA-color:color16
UA-pixels:320x240
x-wap-profile:""
UA-Voice:TRUE
UA-CPU:x86
X-Forwarded-For: 

Thread: 964
Date: 2007-10-25 13:47:03,925
NDC: (null) 

Exception: System.Web.HttpException
Message: Validation of viewstate MAC failed.
If this application is hosted by a Web Farm or cluster, ensure that configuration
specifies the same validationKey and validation
algorithm. AutoGenerate cannot be used in a cluster. Source: System.Web at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) 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() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.test_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec utionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Nested Exception Exception: System.Web.UI.ViewStateException Message: Invalid viewstate. Client IP: Port: 61362 User-Agent: T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; Smartphone; 320x240) ViewState: /wEPDwUJMjUyNTI1NDMyD2QWAmYPZBYCAgEPZBYEAlAPD2QWAh4Kb25rZXlwcmVzcwUqcmV0dXJuIGNsaWNr QnV0dG9uKGV2ZW50LCdjdGwwMF9pYlNlYXJjaCcpZAJWD2QWBAIBD2QWBAIDDw9kFgIfAAUxcmV0dXJuIGNs aWNrQnV0dG9uKGV2ZW50LCdjdGwwMF9jcDFfRmxhc2hCdXR0b24nKWQCBg8UKwACDxYCHghJbWFnZVVybAUj fi9faG9tZV9hZF91bml0cy9ob21lX2FkdW5pdHMxMS5qcGdkDxQrAAMWCB4LQ29vcmRpbmF0ZXMFFzAsMCwy NTUsMCwyMjQsMTEwLDAsMTEwHgtOYXZpZ2F0ZVVybAUGfi9uZmwvHg1BbHRlcm5hdGVUZXh0BSNUaGUgcnVz aCB0byBGYXRoZWFkIGZvb3RiYWxsIGlzIG9uIR4GVGFyZ2V0ZRYIHwIFGzQ5OCwwLDQ1OCwxMTAsMjI0LDEx MCwyNTUsMB8DBRB+L2hlcm9lcy9iYXRtYW4vHwQFOVRoZSBEYXJrIEtuaWdodCBpcyBoZXJlLi4uYW5kIGhl J3MgYnJvdWdodCBzb21lIGZyaWVuZCdzIR8FZRYIHwIFGzcwOCwxMTAsNzM5LDAsNDk4LDAsNDU4LDExMB8D BQZ+L21sYi8fBAUhTUxCIGhpdHMgYSBob21lIHJ1biB3aXRoIEZhdGhlYWQhHwVlFCsBAwICAgICAmQCAw8P FgIeB1Zpc2libGVoZBYCAgEPZBYCZg8PZBYCHwAFMnJldHVybiBjbGlja0J1dHRvbihldmVudCwnY3RsMDBf Y3AxX1N0YXRpY0J1dHRvbicpZBgBBR5f... Nested Exception Exception: System.Web.HttpException Message: Unable to validate data. Source: System.Web at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)

 

Root Cause

This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn’t know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.

And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you’ll see something like this: <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v………tS" />. When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it’s not valid, you get the exception above.

The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn’t see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.

Workarounds

1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:

<pages enableeventvalidation="false" 
    viewstateencryptionmode="Never">

This has the unwanted side-effect of disabling validation and encryption.  On some sites, this may be ok to do, but it isn’t a best practice, especially in publicly facing sites.

 

2. Another way around the problem is to mark the form as disabled and then enable it in script once the load is complete:

  function enableForm() { 
      document.getElementById("form").disabled = false; 
  } 

  window.onLoad = enableForm();

 

Or you can disable the individual form elements and enable them once everything is loaded:

  function disableElements(elements) { 
  for (var i = elements.length - 1; i >= 0; i--) { 
    var elmt = elements[i]; 

    if (!elmt.disabled) { 
      elmt.disabled = true; 
    } 
    else { 
      elmt._wasDisabled = true; 
    } 
  } 
} 

function disableFormElements() { 
  disableElements(_form.getElementsByTagName("INPUT")); 
  disableElements(_form.getElementsByTagName("SELECT")); 
  disableElements(_form.getElementsByTagName("TEXTAREA")); 
  disableElements(_form.getElementsByTagName("BUTTON")); 
  disableElements(_form.getElementsByTagName("A")); 
} 

function enableElements(elements) { 
  for (var i = elements.length - 1; i >= 0; i--) { 
    var elmt = elements[i]; 
    if (!elmt._wasDisabled) { 
      elmt.disabled = false; 
    } 
    else { 
      elmt._wasDisabled = null; 
    } 
  } 
} 

function enableFormElements() { 
  enableElements(_form.getElementsByTagName("INPUT"));
  enableElements(_form.getElementsByTagName("SELECT"));
  enableElements(_form.getElementsByTagName("TEXTAREA"));
  enableElements(_form.getElementsByTagName("BUTTON"));
  enableElements(_form.getElementsByTagName("A"));
} 

Make sure that the variable _form is set to the ASP.net form on the page. Then just call enableFormElements() and disableFormElements().

 

3. The last way to workaround this problem is to override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.  This will ensure that these things get written out before anything that can submit the form:

 

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
  System.IO.StringWriter stringWriter = 
new System.IO.StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); base.Render(htmlWriter); string html = stringWriter.ToString(); string[] aspnet_formelems = new string[5]; aspnet_formelems[0] = "__EVENTTARGET"; aspnet_formelems[1] = "__EVENTARGUMENT"; aspnet_formelems[2] = "__VIEWSTATE"; aspnet_formelems[3] = "__EVENTVALIDATION";
aspnet_formelems[4] = "__VIEWSTATEENCRYPTED"; foreach (string elem in aspnet_formelems) { //Response.Write("input type=""hidden"" name=""" & abc.ToString & """") int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"" + elem.ToString() + "\""); if (StartPoint >= 0) { //does __VIEWSTATE exist? int EndPoint = html.IndexOf("/>", StartPoint) + 2; string ViewStateInput = html.Substring(StartPoint,
EndPoint - StartPoint); html = html.Remove(StartPoint, EndPoint - StartPoint); int FormStart = html.IndexOf("<form"); int EndForm = html.IndexOf(">", FormStart) + 1; if (EndForm >= 0) html = html.Insert(EndForm, ViewStateInput); } } writer.Write(html); }
Update

Another solution based on #3 above, special thanks to Alex for posting this in the comments below.  He wrote a small class called BasePage that fixes the issues, so you just have to extend your page from BasePage instead of Page:

public class BasePage : Page
{
  private static string[] aspNetFormElements = new string[] 
  { 
    "__EVENTTARGET",
    "__EVENTARGUMENT",
    "__VIEWSTATE",
    "__EVENTVALIDATION",
    "__VIEWSTATEENCRYPTED",
  };
 
  protected override void Render(HtmlTextWriter writer)
  {
    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    base.Render(htmlWriter);
    string html = stringWriter.ToString();
    int formStart = html.IndexOf("<form");
    int endForm = -1;
    if (formStart >= 0)
      endForm = html.IndexOf(">", formStart);
 
    if (endForm >= 0)
    {
      StringBuilder viewStateBuilder = new StringBuilder();
      foreach (string element in aspNetFormElements)
      {
        int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
        if (startPoint >= 0 && startPoint > endForm)
        {
          int endPoint = html.IndexOf("/>", startPoint);
          if (endPoint >= 0)
          {
            endPoint += 2;
            string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
            html = html.Remove(startPoint, endPoint - startPoint);
            viewStateBuilder.Append(viewStateInput).Append("\r\n");
          }
        }
      }
 
      if (viewStateBuilder.Length > 0)
      {
        viewStateBuilder.Insert(0, "\r\n");
        html = html.Insert(endForm + 1, viewStateBuilder.ToString());
      }
    }
 
    writer.Write(html);
  }
}

There are many other workarounds for the above mentioned problem; however no definite solution.

Further Information around this problem

ASP.NET Forum link

Connect Bug

Also, if you use Server.Transfer on your page, you you can also run into this issue.  For information on that, take a look at the documentation found here.  Specifically:

If you set preserveForm to true and if the enableViewStateMac attribute of the pages configuration element is true, ASP.NET will raise an exception when Transfer is executed because the view state from the page that calls Transfer is not valid on the destination page. One of the preserved form fields on the calling page is the hidden __VIEWSTATE form field, which holds the view state for the page. When enableViewStateMac is true, ASP.NET runs a message authentication check on the view state of the destination page when the page is posted back from the client and the check will fail.

And there is a KB article on this with a few resolutions.

kick it on DotNetKicks.com

Comments (128)

  1. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  2. Simone says:

    We are having this problem sometimes in subtext when the page is downloaded from slow connections.

    I’ll have a look if I can apply these suggestions to my problem. Than you for sharing

    Simo

  3. Alex Grenz says:

    Thank you for the solutions. I particularly like the third and will use that from now on.

  4. Rob says:

    We used to run into this problem when using large wizard controls. Viewstate would get very bloated and users with slow connections would sometimes click on the “next” button before viewstate was loaded. Our “solution” is to compress viewstate. This really seems to have done the trick:

    http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx

  5. hudo says:

    Only thing that helped me is to add machine key in web.config. And I tried almost everything else…

    You can google for generation tool (http://aspnetresources.com/tools/keycreator.aspx)

  6. That is a very good suggestion Rob, compressing the Viewstate can certainly help in some situations and helps to keep the pages download faster which always helps allowing the entire page to load.

  7. Hudo, that is usually what we have to do if we are using a Webfarm since you want all the processes to use the same MachineKey.

    Take a look at http://support.microsoft.com/kb/312906 for another way, which allows you to create your own tool to create a MachineKey.

  8. ASP.NET – Validation of viewstate MAC failed!

  9. I posted about this some time ago. My previous post: Potential solution for &quot;Validation of viewstate

  10. Last week I was working with on a case where they were getting this error message HttpException (0x80004005):

  11. Rob Achmann says:

    I’ve seen this error on many sites.

    Root Cause? Yes, times for rendering large amounts of viewstate, and ‘premature’ postbacks cause this.

    Think of another area…what about the firewall? What? Firewall? What’s that got to do with rendering web pages? Well, if you have a lot of junk in ViewState, sometimes through no fault of your own, there’s a lot of bits and bytes to go through your firewall. Try to see if your firewall limits, or throttles, the amount of bytes allowed for a single post, or IIS request.

    R.

    Hope that helps.

  12. The firewall is a very good catch also.  We haven’t seen as many of those but it certainly can cause the same problem.  Either increasing the amount of data that it allows through, or trimming the viewstate are the only ways around that.

  13. Tess&#39;s If broken it is, fix it you should blog is always good for a read. Tess is an escalation engineer

  14. bastett says:

    I’ve just tried to implement your override Render method and run into a couple of small problems.

    I don’t really understand this:

    int FormStart = html.IndexOf(">form");

    int EndForm = html.IndexOf("<", FormStart) + 1;

    Surely FormStart will never be true, unless you mean to match "<form" rather than ">form"? Also EndForm would match inside the next tag (in my case a div), so you’d end up with "<<input type…/>div>"

    I changed the IndexOfs to match "<form" and ">" respectively and it seems to work, with the hidden input fields being inserted following the <form> tag.

    Also, in the array of aspnet_formelems, you don’t have the VIEWSTATEENCRYPTED tag. I thought the whole point of the workaround was to put this at the top just after the form tag. So I also added this to your array and the issue seems to be resolved.

    Is this what you meant originally, or have I misinterpreted your solution?

    Thanks,

    Simon

  15. bastett,

    You are right, thanks for finding that.  That is what I get for trying to do the HTML of a < and >.  And good catch on the VIEWSTATEENCRYPTED.  I have updated the post to correct those.

    Thanks

  16. Thomas says:

    A common thread in this is problems with the Viewstate in a hidden field – we use Infragistics GridView controls and the size of the Viewstate field frankly becomes ridicoules as the amount of data displayed increased.

    Possibly this tip from MSDN’s Wicked Code (see figure 4) is a general and recommendable way to work around this problem:

    http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx#S4

    PS. That entire article is excellent and I highly recommend reading it!

  17. Thanks Thomas.  That is a a good article for anyone to read and review.  Storing viewstate in session has good and bad about it, but if you can handle the additional memory on the server, it will work very well and also allows for smaller pages for your clients to download.

  18. Boomport says:

    This solved the problem for me,

    This is caused by the application pool setting on the performance tab, web garden.  Make sure its set to 1, otherwise it will have x app pools who all have different viewstate encryption keys and so it may work if you get the same app pool but the next trip to the server it could bomb if it gets the other app pool.

  19. Yes.  That is a good thing to make sure.  There are other things that can cause this if you are using Web Gardens or a Web Farm

  20. Jai says:

    My webpage works fine on my a workstation but gives “Validation of viewstate

    MAC failed” error when I run it from the PDA.. Any Idea why this wouild be happening? I tried all the solutions given

  21. Jai,

    Is it a large page?  Maybe the PDA has a limit for how much data it will download and cuts off the viewstate.

  22. jai says:

    Page is not large. Let me explain the exact problem

    I have meta refresh tag on the page which refreshes the page every 20 seconds. First time when the page is loaded on the PDA it refreshes without any issues. when the user clicks on a button he is redirected to a different page. After he submits that page he is redirected to the first page with th erefresh meta tag. First page with Refresh meta tag load and when the refresh is happening it throws this error. I hpe I was able to explain the issue. Appreciate your help on this.

  23. Jai,

    If you are on a PDA and refreshing every 20 seconds, do you need viewstate?  Could you turn that off?  If you aren’t using state, that would make the page much smaller also.  Are there controls which you want to keep their state between refreshes?

  24. Martin says:

    Btw…. how can you disable a form?! or enable it?.. it tried your method but it pops a javascript error.

  25. Martin,

    What is the error you are seeing?

  26. PurpleFlux says:

    If you’re getting this error and you’re sure that you are not hosting your web app on a web farm, then this blog post has most of the information you need. All that because someone decided it would be best…

  27. Chris says:

    We’ve been having this exact problem and its caused by having a large page which loads slowly. Your workaround number 3 worked great for us however we’ve noticed a small issue in the html rendered to the page. The __EVENTVALIDATION was rendered in a div at the bottom of the page, however the __EVENTVALIDATION is now rendered at the top of the page which means this div is blank. Firefox seems to handle this fine however IE doesn’t, and it messes up the style of our website. I didn’t write the CSS for the website so I don’t want to go messing around with it as my CSS skills aren’t the best, can you see any issues with me removing the last empty div tag from the html before calling writer.Write(html); in your code?

  28. Chris,

    I don’t see any problem with that.  You should be able to do that without any issues.

  29. shetty says:

    i dono abt these things ..becuase iam a tester …

  30. Jai says:

    I have removed the view state from the page. The issues that I was facing earlier is gone. But now if the user click on teh back button a couple of times he gets this error "Validation of viewstate MAC failed error" Thsi does not happen on the workstation.

  31. Shetty,

    I hope this page helped you then.  Let me know if you have any problems or questions.

  32. Jai,

    The easiest way to track something like that down is if you can reproduce it and then get a network trace to see what is being passed back and forth from the server to the client and vice versa.

  33. raj says:

    Hi All ~ If I am facing the problem after deployment; is there any way out to solve the problem without writing code? otherwise I have to test n create the package again.

    Please reply….

  34. Raj,

    It depends of if you consider changes to your config files changes.  If if it just that the MAC isn’t sync’ed and you are using a web farm.  Otherwise, I don’t know of a way without code changes.

  35. One other thing that can cause errors like this is if there is a second form tag on the page.  So make sure there is just the one form tag that is doing the asp.net post.

  36. Alex says:

    Hi,

    I love your post and the third solution. It really fixed my problem.

    Although there are several potential bugs in your code if the html is not well formed (for whatever reason).

    I’ve written a small class called BasePage that fixes those issues and improves the performance a little bit. Then the only thing to do is to extend BasePage instead of Page.

    Check it out:

       public class BasePage : Page

       {

           private static string[] aspNetFormElements = new string[]

               {

                   "__EVENTTARGET",

                   "__EVENTARGUMENT",

                   "__VIEWSTATE",

                   "__EVENTVALIDATION",

                   "__VIEWSTATEENCRYPTED",

               };

           protected override void Render(HtmlTextWriter writer)

           {

               StringWriter stringWriter = new StringWriter();

               HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

               base.Render(htmlWriter);

               string html = stringWriter.ToString();

               int formStart = html.IndexOf("<form");

               int endForm = -1;

               if (formStart >= 0)

                   endForm = html.IndexOf(">", formStart);

               if (endForm >= 0)

               {

                   StringBuilder viewStateBuilder = new StringBuilder();

                   foreach (string element in aspNetFormElements)

                   {

                       int startPoint = html.IndexOf("<input type="hidden" name="" + element + """);

                       if (startPoint >= 0 && startPoint > endForm)

                       {

                           int endPoint = html.IndexOf("/>", startPoint);

                           if (endPoint >= 0)

                           {

                               endPoint += 2;

                               string viewStateInput = html.Substring(startPoint, endPoint – startPoint);

                               html = html.Remove(startPoint, endPoint – startPoint);

                               viewStateBuilder.Append(viewStateInput).Append("rn");

                           }

                       }

                   }

                   if (viewStateBuilder.Length > 0)

                   {

                       viewStateBuilder.Insert(0, "rn");

                       html = html.Insert(endForm + 1, viewStateBuilder.ToString());

                   }

               }

               writer.Write(html);

           }

       }

  37. Alex,

    Thanks for doing that.  That is very useful.

  38. This is just a quickie to see if that helps anybody. The GridView in GeoTwitter had a problem as was

  39. I’ve introduced a purely javascript based approach that works well enough for me, and doesn’t require you to setup your own string builder (which takes up some memory).

               ScriptManager.RegisterOnSubmitStatement(this, typeof(Page), "form disabler",

    @"

    if(typeof(_PageReadyForSubmit) == ‘undefined’ || _PageReadyForSubmit!= true)

    {

       return false;

    }

    ");

               ScriptManager.RegisterStartupScript(this, typeof(Page), "form re-enabler",

    @"

    _PageReadyForSubmit= true;

    ",

    true);

  40. Clifford,

    Thanks for the additional workaround.  That is also a clean way to do it.

  41. Mike says:

    I had spent a lot of time on tracking down the __EVENTVALIDATION field rendered at end of page issue and finally got here to find the fix. I also noted while here that Studio and NET 3.5 SP1’s had been  released so I updated.

    I go to test the __EVENTVALIDATION BasePage fix and find that my pages are rendering __EVENTVALIDATION much earlier than our QA and PROD servers. We had recently moved to using VS 2008 still compiling for NET 2 so am not sure where this issue is fixed but it appears to be so now.

  42. Dustin Clark says:

    Beware of option 3 if you use Response.write anywhere in your code.  Anything you render using response.write will appear before the very top of your html, regardless of whether it’s called from a .aspx file or from your codebehind.  Using the shortcut <%= %> fixes .aspx files (which i should have been using anyways), but I havent found a solution yet for using Response.Write in codebehind.  I think i’m going to decompile the .NET form class and override the actual rendering of these elements…which seems more efficient than substringing your entire HTML anyways.  I will post the solution if i can figure it out.

  43. Paul Saunders says:

    If you have any other form on the page, and are using the updated option 3, try changing the

    int formStart = html.IndexOf("<form"); line to

    int formStart = html.IndexOf("<form name="aspnetForm"");

    Also if you want this change to apply to all of your pages in your application, create a page adapter override the render emssage in there, as in option 3 update. Then add a browser file to the application, similar to the following:

    <browsers>

    <browser refID="Default">

    <controlAdapters>

    <adapter controlType="System.Web.UI.Page"

     adapterType="MyPageAdapter" />

    </controlAdapters>

    </browser>

    </browsers>

    This will then apply indiscriminately to all pages in the application.

    Thanks for the work around by the way.

  44. J. says:

    This was a great help.  I used Alex’s approach, but made one small change.  Instead of overriding Render:

    protected override void Render(HtmlTextWriter writer)

    I defined a method called RenderFormValidationEarly

    protected void RenderFormValidationEarly(HtmlTextWriter writer)

    Which I call from the pages that testing has shown suffer from this problem.  I’m very happy with it!

  45. Aidas says:

    Hi, I was getting the same error till I used Alex’s approach.  BUT!!!

    1. Now, the first line of a page is "rnrnrn" . What to do?

    2. When a user, after successfull submiting of data, clicks BACK in a Browser and after changing some leters repeats the SUBMIT, he gets "MAC…" ERROR 🙁

    ANY IDEAS?

  46. ton says:

    I translated Alex’s code to VB.NET for the great unwashed heathens who are not coding in C# 🙂

    Imports Microsoft.VisualBasic

    Imports System.io

    Public Class BasePage

       Inherits Page

       Private Shared aspNetFormElements As String() _

       = {"__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "__VIEWSTATEENCRYPTED"}

       Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

           Dim sw As StringWriter = New StringWriter()

           Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(sw)

           MyBase.Render(htmlWriter)

           Dim html As String = sw.ToString()

           Dim formStart As Integer = html.IndexOf("<form")

           Dim endForm As Integer = -1

           If (formStart >= 0) Then

               endForm = html.IndexOf(">", formStart)

           End If

           If (endForm >= 0) Then

               Dim viewStateBuilder As StringBuilder = New StringBuilder()

               For Each element As String In aspNetFormElements

                   Dim startPoint As Integer = html.IndexOf(String.Format("<input type='{0}’ name='{1}’", "hidden", element))

                   If startPoint >= 0 AndAlso startPoint > endForm Then

                       Dim endPoint As Integer = html.IndexOf("/>", startPoint)

                       If (endPoint >= 0) Then

                           endPoint += 2

                           Dim viewStateInput As String = html.Substring(startPoint, endPoint – startPoint)

                           html = html.Remove(startPoint, endPoint – startPoint)

                           viewStateBuilder.Append(viewStateInput).Append("rn")

                       End If

                   End If

               Next

               If (viewStateBuilder.Length > 0) Then

                   viewStateBuilder.Insert(0, "rn")

                   html = html.Insert(endForm + 1, viewStateBuilder.ToString())

               End If

           End If

           writer.Write(html)

       End Sub

    End Class

  47. Naji says:

    i noticed when i used the VB code of solution number 3 that the render code doesn’t find any of "__EVENTVALIDATION" and "__VIEWSTATEENCRYPTED" … etc hiddien fields.

    while debugging the code i found that the problem resides in the following line:

    Dim startPoint As Integer = html.IndexOf(String.Format("<input type='{0}’ name='{1}’", "hidden", element))

    adding watch on that line i found the string produced is:

    <input type=’hidden’ name=’__EVENTARGUMENT’

    the render method doesn’t find this line in the produced html… because its:

    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />

    Notice the double quotations.

    to fix this problem replace that line of code with:

    Dim startPoint As Integer = html.IndexOf(String.Format("<input type=""{0}"" name=""{1}""", "hidden", element))

  48. Naji says:

    Another thing i noticed in the converted code from C# to VB, is the existence of "rn".

    which will produce the following hidden element replacement:

    rn<input type="hidden" name="__EVENTVALIDATION"

    the solution is to replace the following code:

    viewStateBuilder.Append(viewStateInput).Append("rn")

    TO

    viewStateBuilder.Append(viewStateInput).Append(vbCrLf)

    AND FROM

    viewStateBuilder.Insert(0, "rn")

    TO

    viewStateBuilder.Insert(0, vbCrLf)

  49. ton says:

    Naji, good catches I sincerly apologize. It’s just that I had loads of users bugging me about a fix and I was trying to get something out to them to shut them up. But haste always makes waste. I’m posting the revised code for those who need it. I changed all ‘rn” sequences to Environment.Newline’s since its not as platform specific and added double quotes on the attribute fields.

    Imports Microsoft.VisualBasic

    Imports System.io

    Public Class BasePage

       Inherits Page

       Private Shared aspNetFormElements As String() _

       = {“__EVENTTARGET”, “__EVENTARGUMENT”, “__VIEWSTATE”, “__EVENTVALIDATION”, “__VIEWSTATEENCRYPTED”}

          Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

           Dim sw As StringWriter = New StringWriter()

           Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(sw)

           MyBase.Render(htmlWriter)

           Dim html As String = sw.ToString()

           Dim formStart As Integer = html.IndexOf(“<form”)

           Dim endForm As Integer = -1

           If (formStart >= 0) Then

               endForm = html.IndexOf(“>”, formStart)

           End If

           If (endForm >= 0) Then

               Dim viewStateBuilder As StringBuilder = New StringBuilder()

               For Each element As String In aspNetFormElements

                   Dim startPoint As Integer = html.IndexOf(String.Format(“<input type=””{0}”” name=””{1}”””, “hidden”, element))

                   If startPoint >= 0 AndAlso startPoint > endForm Then

                       Dim endPoint As Integer = html.IndexOf(“/>”, startPoint)

                       If (endPoint >= 0) Then

                           endPoint += 2

                           Dim viewStateInput As String = html.Substring(startPoint, endPoint – startPoint)

                           html = html.Remove(startPoint, endPoint – startPoint)

                           viewStateBuilder.Append(viewStateInput).Append(Environment.NewLine)

                       End If

                   End If

               Next

               If (viewStateBuilder.Length > 0) Then

                   viewStateBuilder.Insert(0, Environment.NewLine)

                   html = html.Insert(endForm + 1, viewStateBuilder.ToString())

               End If

           End If

           writer.Write(html)

       End Sub

    End Class

  50. Has everyone tried .NET 3.5 SP1 to see if that resolves the issue for them?  That should take care of this problem without the need for any code workarounds.

  51. ton says:

    Tom from what I understand .NET 3.5 SP1 does solve this issue.  However, the economy is in the toilet at this point and my company isn’t rushing to spend any money on technology upgrades. So unfortunately I’m stuck with .NET 2.0 for the time being. 🙁

  52. ton,

    .NET 3.5 SP1 is a free download that includes .NET 2.0 SP2.  I understand if it is about testing and that knid of stuff with having the new version.  But there isn’t a cost from us for getting this.

  53. ton says:

    Ok so .NET 2.0 SP2 specifically fixes this? Crap I didn’t know. Thanks Tom.

  54. Smcoxon says:

    Hi, I tried the VB versions of this code above. Unfortunately it didn’t quite work for me. I use master pages with a menu based on the.  Using this BasePage approach stops the Menu Friendly Adapter menu from working. Also, in the aspx mark up in the footer of my master page I have:

    <div>

    Copyright © 2006 – <%Response.Write(Year(Now()))%>

    </div>

    When using the BasePage the year now gets written at the top of the page instead of in the footer area. Any ideas on how to fix?

    Regards

    Smcoxon

  55. Smcoxon says:

    I think I’ve resolved my issue…

    I removed the entire mark up in my master page footer <div> and used the master Page Init event to write the text and date in to the footer <div> innerHtml. This seems to work as the year string is no longer written to the top of the page using my original aspx mark up: <% Response.Write(Year(Now()) %>. The Friendly Menu Adapter is also working again by doing this.

    Regards

    Smcoxon

    PS. Any news on when a working 3.5 SP1 will be released?  There seems to be too many reported issues with the beta version to chance installing it.

  56. Jon says:

    Can anyone give me ‘THE’ accepted solution for this problem?

    My problem seems to be related to the fact that I have quite a large wizard control which has 1 user control embedded within each wizard step. One of the wizard steps has a user control with a gridView inside. The gridview also uses the DataKeys feature and I think this is causing the problem.

  57. Zandro says:

    I keep getting the same error. But I was able to solve it. But we have another page that works practically it has the same output and design and it works the different was this.

    We had this the .ASPX page.

       <form name="form1"

         id="form1"

         runat="server"

         action="XXXXXXX.aspx"

         method="post">

    and replaced it with this.

       <form name="form1"  runat="server">

    After making those changes, works like a charm.

  58. Steve Kozyk says:

       I found the current thread we are all reading on http://www.asp.net while I was searching for a problem with my membership and role providers.  I kept getting the following error: "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. Auto Generate cannot be used in a cluster."

       The problem was my login system worked fine on my local machine, but when I FTPed my application to my remote server and then launched it, the user names and roles I created locally would not authenticate.  Login would fail for these users.  If I then created new users with my application on my remote server they would authenticate properly.  In short, any time I moved my application to a new directory the users and roles created when the application resided in previous directories failed.

    I found a solution to the problem that worked for me.  The solution is to manually add the applicationName attribute to the <providers> node of your web.config file and give it a value, such as "/".  I wrote a short article about the process I used to fix the problem.  Hope it helps:

    http://www.itegritygroup.com/itegrity/seo-web-development-blog/index.php/2008/10/validation-viewstate-mac-failed/

  59. Great article. this was exactly the problem i was having with my site <a href="http://www.wordbricks.com&quot; /> ie when people try to add things to the basket before the page has finished loads completely.

    Thanks again.

  60. Jon says:

    Need to use fixed keys to encrypt/decrypt viewstate to avoid postback issues, whether its after long periods or after application pool is recycled.  I found this website for generating these keys for either macnine.config or web.config  http://www.orcsweb.com/articles/aspnetmachinekey.aspx

  61. Baskar rao says:

    Hi all… Nice post. Whether the upgradation to .NET 3.5 or .NET 2.0 SP2 fixes these issues…….

    We here are sick of these viewstate. Our local environment does not get these errors where as these appear to occur in the Prod Servers.

    All the workarounds like keeping same machine key in NLB Servers, and then the workarounds suggested above are applied.

    The only difference is in local we have no firewall where as in Prod there is a Firewall…..

    So what type of settings needs to be addressed in the firewall to allow optimum size of Viewstate…

  62. Baskar,

    How large of a viewstate are you using?  There isn’t really a good size to tell you other then to check what your viewstates are.  You can try disabling viewstate if it is 2.0 and just use controlstate.

  63. Henry says:

    We had issues with __EVENTVALIDATION not being sent with long pages and users doing postbacks prior to page being fully rendered. Installing 2.0 SP2 via 3.5 SP1 seems to have solved it. Thanks for the heads up.

    Maybe the original article should be updated, though. The listed workarounds seem too much of a hassle now.

  64. If you work with web sites in a complex/multi server environment you might be familiar with this error

  65. SRK says:

    In 2008 also i am not able to solve this issue…. can u suggest me another way to solve this ???

    Plz mail me your suggestions at : hallowbestboy@gmail.com

  66. rohit says:

    I am having the same problem. Our system has been in production for about a year, we never had this problem before. Since a week we are getting the following error.

    System.Web.HttpException: The state information is invalid for this page and might be corrupted. —> System.Web.UI.ViewStateException: Invalid viewstate

    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SV1; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.0.3705; .NET CLR 1.1.4322; InfoPath.2)

    ViewState: /wEPDwUKLTg2NjM2NTk1OQ8WBB4JX3BhZ2VNb2RlCylqQVcwM DAwMjguQ3JlZGl0LkNyZWRpdEVkaXQrUGFnZU1vZGVWYWx1ZXMs IEFXMDAwMDI4LCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV 1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAAeF19yZWdpc3Rlcm VkQ2xpZW50RXZlbnRzMvQHAAEAAAD/////AQAAAAAAAAAMAgAAA ElTeXN0ZW0sIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0 cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQE AAAAyU3lzdGVtLkNvbGxlY3Rpb25zLlNwZWNpYWxpemVkLk5hbW VWYWx1ZUNvbGxlY3Rpb24HAAAACFJlYWRPbmx5DEhhc2hQcm92a WRlcghDb21wYXJlcgVDb3VudARLZXlzBlZhbHVlcwdWZXJzaW9u AAMDAAYFAAEyU3lzdGVtLkNvbGxlY3Rpb25zLkNhc2VJbnNlbnN pdGl2ZUhhc2hDb2RlUHJvdmlkZXIqU3lzdGVtLkNvbGxlY3Rpb2 5zLkNhc2VJbnNlbnNpdGl2ZUNvbXBhcmVyCAgCAAAAAAkDAAAAC QQAAAACAAAACQUAAAAJBgAAAAMAAAAEAwAAADJTeXN0ZW0uQ29s bGVjdGlvbnMuQ2FzZUluc2Vuc2l0aXZlSGFzaENvZGVQcm92aWR lcgEAAAAGbV90ZXh0Ax1TeXN0ZW0uR2xvYmFs… —> System.FormatException: Invalid length for a Base-64 char array.

    at System.Convert.FromBase64String(String s)

    at System.Web.UI.ObjectStateFormatter.Deserialize(St ring inputString)

    at System.Web.UI.ObjectStateFormatter.System.Web.UI. IStateFormatter.Deserialize(String serializedState)

    at System.Web.UI.Util.DeserializeWithAssert(IStateFo rmatter 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(Excep tion inner, String persistedState, String errorPageMessage, Boolean macValidationError)

    at System.Web.UI.HiddenFieldPageStatePersister.Load( )

    at System.Web.UI.Page.LoadPageStateFromPersistenceMe dium()

    at System.Web.UI.Page.LoadAllState()

    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

    at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

    at System.Web.UI.Page.ProcessRequest()

    at System.Web.UI.Page.ProcessRequestWithNoAssert(Htt pContext context)

    at System.Web.UI.Page.ProcessRequest(HttpContext context)

    at ASP.credit_creditedit_aspx.ProcessRequest(HttpCon text context)

    at System.Web.HttpApplication.CallHandlerExecutionSt ep.System.Web.HttpApplication.IExecutionStep.Execut e()

    at System.Web.HttpApplication.ExecuteStep(IExecution Step step, Boolean& completedSynchronously) Category: PageError Priority: 5 EventId: 100 Severity

    We are not using a web farm. Our environment is windows 2003 .net 2.0

    The production environment works fine but our SQA system is giving errors.

    Any help is appreciated.

  67. Dustin Clark says:

    I’m still getting this error after installing .NET Framework 3.5, SP1.  In fact, it seems that it is happening more frequently.  However, I can see in the HTML souce that the __EVENTVALIDATION input has moved up to where the other .NET hidden inputs are.  The interesting thing is that now I only get the "Validation of viewstate MAC failed" error, whereas I previously received all three errors mentioned above.

    My theory is that this is happens when a postback is triggered after a session has expired, meaning the postback is the first request of the session.  This can probably happen one of two ways: 1) User sits on a page without doing anything until the session expires, then clicks a button. 2) Client’s browser has cached the HTML from a previous session, so the user views the web page again without initiating a session on the server.  I’m guessing that #2 is more common.

    I know this is happening from looking at click trails.  When the error occurs, the first request of the session is a POST.

    So, I’m going to add the following line of code in my base page:

    Response.Cache.SetNoStore()

    I’m doing this already on pages that require session context.  I’ll do it all all pages and we’ll see what happens.

  68. mike says:

    Update: In my case I was NOT using gridview nor DataKeyNames nor slow loading page.

    Small page with on two buttons, two text boxex, and dropdownlist. Clicking the button1 (add) caused the above error every time.

    Problem turned out to be the form action property was pointing to  a non-existent page! I used a code-behind method when the Add button is clicked and do not use form.submit. When I cleared the action property of the form, problem went away.

    My "guess" is that the form submit happens before

    the code-behind code is processed, since even in debug I would get the error before the breakpoint was hit.

    Hope this leads to the final answer to this.

    thanks!

    Mike.

  69. Pierre Carter says:

    Hello,

    I had the same problem with the Web application installed in IIS 5.1 on Windows XP.  I don’t know if the following text will solve your problem but it solved mine.

    The problem came out only after the machine was updated with the .NET framework 3.5.

    After reading this article 2 or 3 times and after I tried the solutions in the article (did not solve my problem), I discovered, in the problematic Web page, an old attribute in the tag "form".  I had the following in the tag:

    <form id="myForm" runat="server" method="post" action="myForm2.aspx" >

    I just removed the attribute "action" and everything works fine since.

    Hope it helps!

    Regards,

  70. Sam says:

    I am having this error on serveral sites. As usual it appears to be quite random and I’ve never been able to reproduce it consistently. It’s not related to timing either as I have left pages sitting for five minutes, come back and hit a button and received this error. I get this error even though I have disabled viewstate validation!

    Someone at MS needs to pull their forearm out of their backside and do some proper research into this and get it fixed.

    I’m trying out option 3. I’m skeptical, but I’ll see how it goes and report back if I stop seeing the error.

  71. Sam Critchley says:

    Option 3 didn’t make any difference. However, something the client said about leaving the page open for a while and returning later to click on a link was triggering the error.

    So I have disabled session state (nvr use the thing) and I’ll see if that works out.

  72. Apps says:

    I insatlled the .NET 3.5 SP1 (.NET 2.0 SP2) from the above source. Still the error persistes.

    I have no luck in resolving this error

  73. Apps,

    Do you know what the situation is around when you get the error?  Can you repro it?

    Have any of the other workarounds helped?

  74. Alexis says:

    How do I use Alex Class in a project?

  75. J. Hellborg says:

    Using a load testing tool, I can reproduce it by changing the Web Garden figure to > 1. The higher the wg figure the more Viewstate errors my load test will generate ( though the overall number is small, around 1% of completed tests )

    1 wg = 1 w3wp.exe process

    2 wg = 2 w3wp.exe processes

    I’m guessing something gets mixed up with the wrong thread handling the another threads request, occasionally.

  76. Nicolas says:

    For those who need ASP.NET machine keys and French explanations, I wrote a simple generator you can find on my personal web site http://muniere.fr/Projects/KeysGenerator/

    Hope it helps!

    Nico

  77. Doug says:

    I’m as well getting this error, mostly on the test server. It happens unpredictablely.

    My question is, can someone cause the error simply? Then it would be much easier to test these solutions.

    Basically, our app will timeout, and the login page, usually after sitting un-used for long periods of time will throw the error. Its occurred in localhost a handful of times.

    It would be nice to know if the error can be triggered easily, so I don’t have to wait for app timeouts to fire, session timeouts to end. Maybe there is not a simple way, but just thought i would ask?

    thanks

  78. I had this issue and found the cause to be the following.  

    I had a GridView with ButtonFields, and a Form.   The form action was set to post to page "X".  Later in my code, I caught the Selected Changed event of the GridView when the ButtonField was clicked or "Selected".  At that point I did a Server.Transfer to page X with the a data value in the row selected.  Basically when they selected a row in the grid i sent them to a details page of that row.  Turns out, I needed to remove the "action" from the form, and then it worked fine with no issues.  My environment is Windows Server 2003, .Net 2.0

  79. Jerome says:

    Hello,

    i have the same error but only on a web server under win 2008 et IIS 7, under IIS6 and win 2003 or from my development server (visual studio webserver) to the win 2008 server, there is no problem.

    I explained my configuration : i have two web sites on my server, ws1 and ws2. The site ws2 try to send values to ws1 by posting them with an asp:linkbutton and the postbackurl property defines to ws1, http://ws1/default.aspx.

    You can contact me with my email publicNOSPAM@NOSPAM.bfd.fr . (Don’t forget to remove NOSPAM).

    Thanks

  80. Thom says:

    In my case, this error was caused by hitting a site memory cap instituted by my web hosting company.  They increased my limit and it went away.

  81. slayton says:

    Hi.  This is great information, thank you!  I also encountered this exact issue and error message in the large web app that I program and support and uses .NET.  Interestingly (or maybe not, I didn’t ready every comment).  

    It seems though my experience of resolving the issue went like this.  My issue kept coming back whenever I upgrade to .NET 2.0 SP2.  If I installed any .NET package 2.0 SP2 or 3.0 and 3.5 that took .NET 2.0 to SP2, my page would break.  And I got all kinds of results installing different packages.  

    In order to work this whole mess out, I started with uninstalling all .NET versions > 1.0.  

    Then installed 2.0.50727.42.  

    > the page worked

    Then installed when I started installing .NET 3.0 and 3.5, it included updates on .NET 2.0 that took it to SP2.  

    > page wouldn’t work

    I did a bunch of tests (unistalling/reinstalling all .NET versions) with a variety of 2.0, 3.0 and 3.5 packages available if any of them took .NET 2.0 to 2.0.50727.3053 or upward to 2.0.50727.3082 the page would not work.  However, there was ONE exception of having the page work when .NET 2.0.50727.3053 was installed via 3.0 SP1 which also installed 3.0.4506.2152.  Although, it seems I was not able to repeat that result.  So I will stick by what I am saying about 2…3053 for now.

    The bottom line  was that I was able to get .NET frameworks for 2.0, 3.0 and 3.5 that kept my page working by installing .NET 3.5 (NOTE: NO SERVICE PACK).  This installed

    .NET 2.0.00050727.1433

    .NET 3.0.4506.648

    and .NET 3.5.????? (not sure of the rest of the version)

    Does any of this make sense?  Anyone else encounter this? or perhaps unknowningly you got a visit from the Windows blind link fairy and installed packages that was not full .NET 2.0 SP2.

    By the way, here is a neat little app that allowed me to get deep into version numbers.  It isn’t updated for 3.5 yet but I imagine it will be soon….

    http://www.tmgdevelopment.co.uk/versioncheck.htm

    I will check back for thoughts or questions on this whole version experiement…know that the results above are greatly summarized.

    Slayton

  82. Slayton says:

    I should also mention the work I did was on W2k3 SP2 and IIS6.

  83. Chan Kok Kiet says:

    Hi,

    I hit this error only if I implemented server side viewstate to my web app, and have callback.

    Any ideas?

    Thank you

  84. Tim says:

    Just wanted to comment.  We are using .NET 3.5 SP1 (which mean .NET 2.0 SP2) and we have a "fixed" MachineKey setting.  This issue is STILL happening.  So I will look at some of these resolutions and try to come up with something that works.

  85. Greg says:

    Excellent post!!

    2 days spent looking for the reason for this untill I spotted that the __EventValidation is missing altogether!

  86. molotov says:

    FIX: Error message on an ASP.NET page after you submit a form that has the "action" attribute defined after you install the .NET Framework 2.0 SP2 or the .NET Framework 3.5 SP1: "Validation of viewstate MAC failed" @ http://support.microsoft.com/kb/970459

  87. René says:

    About WorkAround 3, the C# BasePage class, how do you inherit this page, when I put in behind Inherits in my .aspx file, I get an error saying it needs a different Model.

  88. Vishal says:

    I am still getting this Error, I have .net 2.0 with SP 2.

    Error:

    System.Web.HttpException was unhandled by user code

     ErrorCode=-2147467259

     Message="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="System.Web"

     StackTrace:

          at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)

          at System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState)

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

          at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()

          at CTL.COM.PRIME.WebApplications.Common.PageBase.LoadPageStateFromPersistenceMedium() in C:ProjectsWebApplicationsCommonModulesPageX.vb:line 331

          at System.Web.UI.Page.LoadAllState()

          at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

  89. Anita says:

    I tried Basepage third Solution but still it showing error , any idea to fix it?

  90. Patrick says:

    Has anyone seen a different solution?  I’ve tried just about everything I can on this page and nothing works.

  91. patibandha says:

    we are getting this error in Chrome only..

    in IE and other it is working fine. but only on chrome if i use history back btn then i execute the page.. it is giving me this error..

    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.

    as i read many problems related to this.. but they are not Chrome related.

    any idea..

  92. Ron says:

    Actually, we’re not using a farm server, we’re not using anything that uses DataKeyNames (or anything that databinds for that matter), and the page is fairly small, but this error will come up after the webpage has been left open for quite some time, and the user attempts to make a postback.

    Anyone got some ideas?

  93. Wendell says:

    Everything that was posted here did not solved the issue. In our DEV machine it was working fine. But in our PRD servers. it was not working same issues that you reported. Has this something to do with Firewalls? Maybe we’re fixing here that was not the main issue at all? any ideas? updates?

  94. One thing you can do is use one of the available ViewState Decoders to look at the ViewState and see what it looks like.  The main thing to look for is if it is getting cut off.  You can find a couple of decoders on Scott’s blog at:

    http://weblogs.asp.net/scottgu/archive/2003/02/16/2495.aspx

  95. Tony says:

    Re: Ron’s comment – I have exactly the same issue – if the page is left open for some time, then I click a link to open a popup and perform a callback to rebind some data, I’ll get the viewstate error everytime.  Seems to be linked to the session timeout.  Out of options now!

  96. Jandler says:

    Unfortunately, the issue still occurred for me. I installed the latest SP and when I run the app through VS2008 and perform the clicking, the error still persist.

  97. arun says:

    i am inheriting my page from BasePage

    but still i am getting this error then what may be the cause for it ?

    plz mail me at aruninnice@gmail.com

  98. Alok Kumar says:

    We had removed the action tag and it worked for us.

  99. tchimev says:

    I have the same situation as Ron and Tony has.

    If I left a page open for a while and than post back, the page redirects with Response.Redirect to login page. Than I try to login and on the first post back on the login page I get the error.

  100. SPandey says:

    hello,

    I was working on VS2005 Team Suite with 2.0 framework.

    I update my Win XP with SP3 and Other Updates.

    Now i have 2.0SP2,3.0SP2,3.5SP1.

    I didnt upgrade my project from 2.0.

    Afret that i start facing the above prob(<machine…..>).

    I add machine tag under  <system.web> tag and problem solves,

    I am confused why this error occures.

    I shoot a mail to MS Support team too.

    If anyone has answer pls answer.

    Regards.

    SPandey

  101. Brian says:

    You asked if this is still happening even after SP1, and yes it is.

    I have a site with a master page and a form page, my form is nothing but a simple user registration, I have no grids or large controls. My Viewstate is tiny as I am dealing with 10 textboxes and 12 checkboxes. this is supposed to be a 1 hour job creating a page that grabs this little data and sending it to a DB.

    I am running vista, vs 2008 sp1 and IE 8

    I am bothered by the amount of workarounds here and no solutions to the actual problem.

    I guess I will go and trial and error my way through the workarounds.

  102. John Smith says:

    Very interesting.  I have vs 2008 sp1 for asp.net.

    I had this error come up when going from localhost to a commercial server.  Everything worked fine on localhost (the server running under Visual Studio’s IDE).  Here is what I did, and I’m not sure all three steps are necessary, in fact, I think the real reason is at the end of this post.

    1.  I did add in Web.Config a "machine key" entry, which before was lacking.  I used this website: http://aspnetresources.com/tools/keycreator.aspx   Honestly, I don’t think this was the solution, but it did not hurt.

    2.  I did _not_ play around with any default settings for any of the below–but here is what others say works (which I did not do):

    validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" EnableViewStateMac="false" EnableViewState="false".

    In fact, I found that all of these switches are mutually incompatible when put together (my program would not run with all these parameters set they way they are above).  In other words, I left all of these switches in the default state (I did *not* explicity overwrite them as some have suggested).

    3. I changed, as per this Microsoft suggestion, http://support.microsoft.com/kb/316920/ , all Server.Transform (…, true) to (…, false) [the default].  In other words, I dropped the true switch.

    4.  Whenever possible–and I don’t think this matters at all, but I mention it anyway–I used Response.Redirect rather than Server.Transfer.  But I emphasize this is probably not important at all.  Just relating what I did.

    5.  Most importantly–and you more senior programmers should get a good laugh out of this–I found the bottleneck in my program and eliminated it–so that the program was not "waiting" a long while, and "consuming" a lot of resources.  The way it was before, I was using using System.Threading; and had many threads open.  I notice this error would result when a lot of time passed with a window open (and threads running at the server)–and the user did not even have to do anything–but at the 3 minute mark the error would appear (give or take 20 seconds).  So I eliminated the bottleneck in my program, and voila!–like magic the error disappeared!  Strangely, after doing the above, now I can even go past three minutes and no error results.  Which raises my final (and I think my best) point:

    So–what do I think caused the error?  I’m not sure, but here’s my hypothesis:  when I published my app, which was running fine (albeit with the bottleneck very sluggish) onto the commercial ASP.NET web hosting site I use, the problems arose because, as a previous poster in this thread has stated, I was not given a lot of memory at this company’s servers (which makes sense since I’m not paying them much).  Consequently, my bloated program was consuming a lot of memory and/or resources at their server(s), and after 3 minutes or so the site’s server memory manager (sorry for my lingo–does such a thing even exist?) at the server site was cutting me off…in other words, it was not so much my code at fault but the limited memory allocation I was given by the site I’m using–I’m not sure on this, but I think that’s the real reason.  In short: once I made my program more efficient, and the resources consumed by my program were not ‘ballooning’, the error disappeared.

  103. Hey everyone, I am looking for someone that has this problem that is willing to work with Microsoft to try to get it resolved.  I am interested in someone that has the 3.5 SP1 (.NET 2.0 SP2) installed and is still seeing the problem.  We want someone that has this reproduced that we can work with to fix it better.  If you are willing to help, please send me an email from http://blogs.msdn.com/tom/contact.aspx

    Thanks

  104. BSentosa says:

    Hi Tom,

    I’m still seeing the problem though I tried to implement Alex’s code. My problem is only appearing when I use other browser than IE. The scenario is, after user logout from the session, it will be redirect to other website. Then user click back button from browser and try to login again (Submit) from the login page, the message of "Validation of viewstate MAC failed error" appear. I’m using master page and .NET 2.0 SP2. But if we force the browser to reload, the message is gone. It is only happen to Chrome, Firefox, and Safari. It’s just nice in IE. I’ve tried to use workaround option 1 and also your code, but was not successful. It’s just weird since the error only being shown for other browser.

  105. Marc says:

    I am trying Ton's VB.net solution today as all other web.config settings suggested do not resolve the problem. I will advise if it works for two live busy sites where these invalid viewstate messages occur about 10 times per day. (Net 2.0  IE 6 7 or  8 )

    Thank you everyone for trying!

  106. Hugh says:

    my application is using framework 4.0 and still has the problem.  

  107. yunus says:

    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.

    i am getting above error can  someone help me out?

  108. yunus,

    Have you tried setting the machineKey to be the same on all servers?

  109. MY says:

    For me only adding the machineKey -Element (created by the machineKey generator) into the Web.Config file solved the issue. Thanks for the contribution to all!

  110. Hans says:

    Tom, do you understand WHY the machineKey should be the same on all servers in a web farm or cluster? The reason is that the viewstate is encrypted using the machine key. Once you inderstand that, then you would als understand why a machine key should be added when you only have 1 server instead of using your "workaround". Becaue when you don't  use a machineKey, ASP.NET will generate one for you. Which i no problem untill the ASP.NET worker process recycles. When this happens between 2 postbacks, the viewstate which has been encrypted using the first generated machine key cannot be decrypted anymore using the newly generated machine key, resulting in thi error. So adding a machineKey will solve thi error withhout uing your workarounds…..

  111. Lyndon says:

    Had the same issue. After much digging, found it was caused by the form having a different action to the current URL due to URL Rewriting.

    The page in question has a DataList with a control to advance to the next page. On the first page everything is fine. On any other DataList page I get the Validation error if I press any anything that causes a postback event. The displaying of pages for the DataList is controlled by a QueryString  parameter.

    The fix was simply to overwrite the form action in the page prerender function so that it matches the URL on display in the address bar.

    Actual URL:

    /site/ShowCategory.aspx?categoryid=106&page=2

    User sees (through URL rewriting):

    /site/c106/the category description/p-2

    Without overwriting the form action, the system was setting the action to:

    /site/p-2?category=106&page=2

    – it was this that was causing the issue. On inspection it looks like the system was taking the user readable URL and determining the page to be p-2, then taking the querystring after the transformation and adding it to the back end of the URL – creating total garbage.

    Hope this helps others that may have a similar issue.

  112. Chen Xiufei says:

    I had this problem too. The reason is that webpages in one browser(IE 7) are always out of date(due to the browser settings). I think it will be solved by adding a machinekey, so that the viewstate value will not be changed.

    I'm using .net 2.0, workaround 1 didn't solve the problem. And there was an javascript error when I used workaround 3 in IE 6.

    Thanks for all the posts, I learned more on the possible causes of this exception.

  113. bugbucket says:

    Tried BasePage class, .NET 3.5 SP1 and still get Viewstate MAC errors.

  114. Hong says:

    I have this problem after logging on when session expires.

    The following is an example:

    1.  Long inactivity.

    2. Accessing http://localhost/app/foo.aspx?ticker=tto.

    3. Directed to http://localhost/app/Logon.aspx

    4. Log on

    5. Error with the following address: http://localhost/app/Logon.aspx?ReturnUrl=%2fapp%2ffoo.aspx%3fticker%3dTTO&ticker=TTO

  115. Mark says:

    In my website i did a mail-send form based on ASP.NET with MailMessege.

    At the beginning it worked fine but now that problem occurs.

    Can you help me please?

    The website is in hebrew: http://www.habaithakatom.co.il

  116. John Heal says:

    I was getting the same error without a webfarm, but only after a form with a gridview was left open and unused for some time. In this case it turned out to be occurring as the session had expired (set by default to 20 mins). I had two applications with this issue, one was solved as I had to use forms authentication and you just login again after session expires. The other was sorted by increasing the session timeout in the web.config.

  117. dtwilliams says:

    The ViewBasket.aspx and ViewBasket.aspx.vb code-behind are incorrectly referencing the orderConfirmation page/class.

    Replace any instances of orderConfirmation with ViewBasket and it works as it should.

  118. Ned says:

    I am seeing this error on an asp.net 2.0 formview with about 50 controls (radio buttons, checkboxes, textboxes). The page does a lot of validation, to make sure that for example exactly 3 out of 11 checkboxes are checked.  I am not an expert coder and am not sure I understand the suggested workarounds about overriding the Render method or disabling the form and then re-enabling it.  I am also not sure I understand what this has to do with the viewstate failing to load before the page is submitted — since the controls do not have default values set, it takes the human user some time (probably 5-10 minutes) to go through the form, clicking on things, so how can it not have completely loaded yet?

    My question is: since I am not using the formview's built-in Update functionality — the update button has no Commandname property but instead its Onclick calls a subroutine that sets all the SQLDatasource's update parameters and then calls update() — do I even need the formview's DataKeyNames attribute?  It seems to work without it.  And if I omit DataKeyNames can I avoid this error?  In our case it is an intermittent error anyway.  

    At this point, the alternative I am facing is to take some time to break up the form into 4 or 5 pages, which might be a good idea anyway — I'm not sure which is more annoying to the user, filling out a very long form or filling out 4 or 5 shorter ones.

    Thanks.

  119. I converted this code to VB (not that I wanted to, but the website I'm maintaining is written in VB):

       Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)

           Dim stringWriter As StringWriter = New StringWriter()

           Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)

           MyBase.Render(htmlWriter)

           Dim html As String = stringWriter.ToString()

           Dim aspnet_formelems(4) As String

           aspnet_formelems(0) = "__EVENTTARGET"

           aspnet_formelems(1) = "__EVENTARGUMENT"

           aspnet_formelems(2) = "__VIEWSTATE"

           aspnet_formelems(3) = "__EVENTVALIDATION"

           aspnet_formelems(4) = "__VIEWSTATEENCRYPTED"

           For Each elem As String In aspnet_formelems

               'Response.Write("input type=""hidden"" name=""" & abc.ToString & """")

               Dim StartPoint As Integer = html.IndexOf("<input type=""hidden"" name=""" + elem.ToString() + """")

               If StartPoint >= 0 Then

                   'does __VIEWSTATE exist?

                   Dim EndPoint As Integer = html.IndexOf("/>", StartPoint) + 2

                   Dim ViewStateInput As String = html.Substring(StartPoint, EndPoint – StartPoint)

                   html = html.Remove(StartPoint, EndPoint – StartPoint)

                   Dim FormStart As Integer = html.IndexOf("<form")

                   Dim EndForm As Integer = html.IndexOf(">", FormStart) + 1

                   If EndForm >= 0 Then

                       html = html.Insert(EndForm, ViewStateInput)

                   End If

               End If

           Next

           writer.Write(html)

       End Sub

  120. Rajesh says:

    I was facing the same problem but in my case the problem was that I have the wrong action name in the form tag which was causing the problem.

     <form action="improvethought.aspx" method="post" id="addForm" runat="server">.

    correcting the action name solved my problem.

    Thanks  

  121. ran into this same issue with APP running on .NET 4.0. Two different environments using load balancing. On one resetting the sticky sessions from 3 to 30 minutes resolved the issue and on the other turning off JsessionID in the balancer resolved the issue.

  122. Gaurav says:

    Thanks for detailed information about cause and solution to fix it.

  123. Sunil says:

    Hi,

    I am getting "invalid viewstate exception" even after trying all the options discussed above. I am using asp.net 4.0. I see this exception when I use ViewStateEncryptionMode="Always" property. I have a requirement to encrypt the viewstate for security reasons. Please let me know if you have some other solution for this when has not been discussed above.

  124. WoundedEgo says:

    I tried adding a machine key and inheriting from BasePage and got the same error. My workaround is to use Response.Redirect().

  125. Gautam Das says:

    I have getting Error  state information is invalid for this page and might be corrupted  after I set viewstateMac=true .If I set viewstateMac=false then page is running fine. but due to cross site scripting I need to set it true please give me the solution for that.

    Thanks

    Gautam

  126. I think the 3rd solution, by Alex, solve my problem.

    Thanks.

  127. nnbaliga says:

    ARR 3.0: Client Affinity Not Working

    Even though I have set the Client Affinity in my server farm, the requests from same client are sent to different servers.  This behavior I have confirmed in Monitoring and Management section in the server farm. Also I am getting following error in the client,

    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.

    Any solution ?

  128. Ami Schreiber says:

    Yeah…so none of these suggestions work if you're using SharePoint with MasterPages enabled. Try creating a custom upload form that is required to both allow the user to upload a file and save data entered by the user via custom field types on the same form and see what happens.

    Wait for it…

    Wait for it…

    Boom!

Skip to main content