iis负载异常:
Unable to validate data. at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) HttpApplication.RaiseOnError => EventHandler.Invoke => Global.Application_Error
如果你的Asp.Net程序执行时碰到这种错误:“验证视图状态 MAC 失败。如果此应用程序由网络场或群集承载,请确保 <machineKey> 配置指定了相同的 validationKey 和验证算法。不能在群集中使用 AutoGenerate。” 那么说明你没有让你的应用程序使用统一的machineKey,那么machineKey的作用是什么呢?按照MSDN的标准说法:“对密钥进行配置,以 便将其用于对 Forms 身份验证 Cookie 数据和视图状态数据进行加密和解密,并将其用于对进程外会话状态标识进行验证。”也就是说Asp.Net的很多加密,都是依赖于machineKey里面 的值,例如Forms 身份验证 Cookie、ViewState的加密。默认情况下,Asp.Net的配置是自己动态生成,如果单台服务器当然没问题,但是如果多台服务器负载均 衡,machineKey还采用动态生成的方式,每台服务器上的machinekey值不一致,就导致加密出来的结果也不一致,不能共享验证和 ViewState,所以对于多台服务器负载均衡的情况,一定要在每台站点配置相同的machineKey。
machineKey生成的算法:
validationKey = CreateKey(20);
decryptionKey = CreateKey(24);
protected string CreateKey(int len)
{
byte[] bytes = new byte[len];
new RNGCryptoServiceProvider().GetBytes(bytes);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.Length; i++)
{
sb.Append(string.Format("{0:X2}",bytes[i]));
}
return sb.ToString();
}
附参考的matchineKey配置:
<?xml version="1.0"?>
<configuration>
<system.web>
<machineKey validationKey="3FF1E929BC0534950B0920A7B59FA698BD02DFE8" decryptionKey="280450BB36319B474C996B506A95AEDF9B51211B1D2B7A77" decryption="3DES" validation="SHA1"/>
</system.web>
</configuration>
-----------------
加密MachineKey
<machineKey validationKey="XXXXXX" decryptionKey="XXX" validation="SHA1" />
validationKey可以为视图状态、身份验证Cookie、Session等重要的信息添加杂乱信息以防止重要信息被篡改。
为了防止validationKey和decryptionKey以明文的方式进行显示,可以使用ProtectSection方法对machineKey配置节进行加密。
1、在Web.config中添加原始的配置,如:
<machineKey validationKey="XXXXXX" decryptionKey="XXX" validation="SHA1" />
2、通过程序对system.web/machineKey节进行加密和解密
加密方式如下:























如果想变回原来的明文显示可以执行解密的相反过程就行
注意:其中的OpenWebConfiguration("/");表示打开站点根目录下的web.config,其它情况可参考如下:
Using the Management API