EnableViewStateMac in an ASPX Page ASP.Net

Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed.

Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.

ASP.NET ViewState is tied to the particular server it came from by default-- even though the documentation says it isn't. So when ViewState generated on server A is POST-ed back to server B, you'll get this exception. Somewhere in the pipeline, the viewstate is salted with a unique, autogenerated machine key from the originating server's machine.config file:

<!-- validation="[SHA1|MD5|3DES]" -->
<machineKey validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps" validation="SHA1"/>

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 :

<!-- validation="[SHA1|MD5|3DES]" -->
<machineKey validation="SHA1"
validationKey="F3690E7A3143C185A6A8B4D81FD55DD7A69EEAA3B32A6AE813ECEEC" />

Or you can disable the keying of viewstate to a particular server using a simple page directive at the top of your .aspx pages:

<%@ Page Language="C#" AutoEventWireup="false" Codebehind="DemoPage.aspx.cs"
Inherits="DemoAssembly.DemoPage" enableViewStateMac="False" %>

Alternately, you can modify the pages element in Web.config:

<system.web>
<pages enableViewStateMac="false" />
</system.web>
Tags: , ,
Hot on Web:


About author