Setting ViewStateUserKey gives me a "Validation of viewstate MAC failed" error

Druid picture Druid · Sep 13, 2009 · Viewed 32.8k times · Source

I have the following in my BasePage class which all my ASPX pages derive from:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    ViewStateUserKey = Session.SessionID;
}

I also have a machineKey set in Web.config. I don't think this error is because of a web farm because this happens on my dev machine too.

My host has now upgraded to .NET 3.5 SP1. After this update, everytime I compile with the ViewStateUserKey setting above, I constantly get the "Validation of viewstate MAC failed" error on every postback.

What am I doing wrong here? Is this setting even necessary anymore with the latest framework update?

Answer

Adam Tuliper - MSFT picture Adam Tuliper - MSFT · Sep 30, 2010

OK - Im a year late to the conversation - but how is this the correct answer? This applies only in the case of authenticated users and using the ViewStateUserKey as the username is a lot easier to guess than a session id GUID.

BTW if you want to 'fix' the code up top, use the Session ID, however you must set a session variable in order for the session id to stop from changing every time. Ex. Session["Anything"] = DateTime.Now

ViewStateUserKey = Session.SessionID;

This of course is assuming you are going to use sessions, otherwise you need some other key to use such as the username or any other guid kept in a cookie.