how to stop viewstate going stale?

227 views Asked by At

I have an ASP.NET web forms app which uses HTML5 "Offline Web Apps" technology to store pages in the browser cache for an extended period of time. In this case it's possible for a user to press a button on the form and do a postback when it's days or weeks since the form was fetched from the server (i.e. a long time interval between the GET and POST requests).

Sometimes, this postback fails with the classic "Validation of viewstate MAC failed". My question is in 2 parts:

  1. What causes the viewstate to go stale? i.e. how can I replicate the problem on demand?

  2. Is there anything I can do to make sure this never happens? bearing in mind that there is advice saying I should never disable viewstate MAC.

1

There are 1 answers

4
johna On BEST ANSWER

You may be able to solve this by adding a machine key to your web.config file.

You can use an online tool to generate a machine key, eg. http://www.developerfusion.com/tools/generatemachinekey/.

In the web.config it goes under configuration > system.web.

It won't help, though, if you make changes to your web form or form ListItem values, etc.

You may be best not using an ASP.NET form and instead submitting via AJAX or using an HTML form (but still using ASP.NET Web Forms).

Updated

One of the reasons ViewState can go "stale" is if the application pool recycles or stops/restarts. Default settings in IIS will result in your website shutting down if there are no requests within a certain amount of time then restarting again when a request comes in.

One way you can test is to (1) open a web form on your site (2) make a change to your web.config file and resave (3) submit the form. If you don't have a machine key you will get a viewstate error at this point.