Thursday, July 31, 2008

Web Farms and ASP.NET ViewState

"The default ASP.NET settings ensure that forms authentication tickets are tamper proof and encrypted, and that ViewState is tamper proof. This ensures that any modification of the ViewState or authentication tickets either on the client's computer or over the network is detected when the server processes the data."
 
For example, when the viewstate generated on server A is posted back to server B you may receive a viewstate validation error if the <machineKey> is not the same on all of the servers in the web farm or cluster.
 
Here is one of the exceptions you may receive:
 
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.
 
This is because the viewstate is salted with a unique, autogenerated machine key from the originating server's machine.config file.
 
"This is done to prevent users from somehow tampering with the ViewState. Any change to the ViewState data on the client will be detected. But this has a side effect: it also prevents multiple servers from processing the same ViewState. One solution is to force every server in your farm to use the same key -- generate a hex encoded 64-bit or 128-bit <machineKey> and put that in each server's machine.config"
 
If you do not have access to the machine.config files in the web farm or cluster you can disable the enableViewStateMac using a simple page directive:
 
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="MyPage.aspx.vb"
 Inherits="MyAssembly.MyPage" enableViewStateMac="false" %>
 
Alternately, you can modify the pages element in Web.config:
 
<system.web>
  <pages enableViewStateMac="false" />
</system.web>

Of course caution should be taken when setting the enableViewStateMac to false since the viewstate could potentially be tampered with.
 
If you have a web farm or cluster and receive this error the optimal solution would be to update the machine.config files on all of the servers in the web farm or cluster to ensure that the <machineKey> configuration specifies the same validationKey and validation algorithm.
 
 
 

0 comments: