获取“身份验证失败。 System.InvalidOperationException” jquery 调用 Webmethod 时出现间歇性错误

Getting “Authentication failed. System.InvalidOperationException” error intermittently with jquery call to Webmethod

我在 ASP.NET Webform 中有一个 WebMethod,位于 foo.aspx 页面的代码后面

    [WebMethod]
    public static String foo()
    {
       return "";
    }

我使用 jQuery

调用它
        $.ajax({
            type: "POST",
            url: '<%= ResolveUrl("foo.aspx/foo")%>',
            data: JSON.stringify(dataToServer),
            contentType: "application/json; charset=utf-8",
            success: function (data ) {
                 // work with data here
            }
        });

这是来自服务器的响应头

Request   
Request Method:POST
Status Code:401 Unauthorized
2:2
Cache-Control:private
Content-Length:105
Content-Type:application/json; charset=utf-8
Date:Tue, 20 Jan 2015 04:40:36 GMT
jsonerror:true
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET

响应正文

{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

背景资料

The application works just fine in the testing environment with a single web server. Only when deployed to a web farm then this problem happens.

当 encryption/decryption 键在所有实例中不匹配时通常会发生这种情况

如果您使用 SHA1 来散列密码,您需要确保网站的所有实例共享相同的 machineKey,以便散列算法可以正确散列密码。

您可以通过将相应的键添加到 web.config 文件来实现,例如...

<machineKey decryption="AES" 
            validation="SHA1" 
            decryptionKey="22B83C3D43B0BA0E2" 
            validationKey="1C059088E7E510C83650449D8D6567B2" />

如与 ...key 值相关的 machineKey 元素的 MSDN 文档中引用...

Specifies a manually assigned key. This value must be manually set to a string of hexadecimal characters to ensure consistent configuration across a Web farm. The key should be 16 hexadecimal characters in length when using DES encryption and 48 hexadecimal characters in length when using Triple DES (3DES) or AES encryption. If keys shorter than the maximum length are used, the keys should be created by a truly random means, such as by using the RNGCryptoServiceProvider class. ASP.NET can use Triple DES only on computers on which 128-bit encryption is available.

有关信息,请参阅 MSDN