Monday, 25 January 2010

Invalid ViewState and WebResource.axd errors

Form submission

ViewState includes a Message Authentication Code (MAC). The MAC is generated using a validation key on the server. When the form is posted back the server compares the MAC in the ViewState with one regenerated on the server. If they differ the ViewState is regarded as invalid.

The value of the MAC can change when:

  • Data in the ViewState has changed (e.g. a hack attempt)
  • Truncated form data (e.g. timeout)
  • Using Server.Transfer can cause it to happen
  • The validation key used to generate the ViewState MAC is different than the key being used to generate the MAC for comparison

Note that the validation key may be different on different servers in a farm. You must take steps to ensure the validation keys match across machines. Validation keys can be different across application pools. Validation keys can change if the application pool restarts (e.g. if the key is set to AutoGenerate).

To avoid MAC mismatches:

  • Don't use the ViewState if you don't need to.
  • Turn off MAC generation by setting enableViewStateMac=false in the page or web.config. NOT RECOMMENDED!
  • Prevent your application pool from restarting by disabling the auto recycle and idle timeout settings in the application pool.
  • Hard-code the MAC validation key so that it's always the same (good for web farms). Hardcode the key in the <machineKey> tag in the machine.config or web.config.

See http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx for a detailed overview.

Web resources

Similar issues can affect web resources accessed via webresource.axd. Requests to web resources will include a ‘d’ parameter (decryption key?). As such it is subject to the same issues with the key changing as above. This key will be an encrypted version of the web resource identifier used to retrieve the resource from the appropriate assembly.

One way in which web resources can be used is in Ajax or other JavaScript enabled web controls by adding the [WebResource] attribute to reference JavaScript files stored as resources. When the control is rendered on the page a reference to the script file will be generated as a request to webresource.axd

Also be aware of ScriptResource.axd (which contains all of the client-side JavaScript for Ajax) in web.config files.

Problems with web resources etc can give rise to the “Padding is invalid and cannot be removed” errors.

See http://msdn.microsoft.com/en-us/library/system.web.ui.webresourceattribute.aspx and http://msdn.microsoft.com/en-us/library/system.web.handlers.scriptresourcehandler.aspx.