【问题标题】:Authentication failed error when calling web method using $.ajax使用 $.ajax 调用 Web 方法时出现身份验证失败错误
【发布时间】:2015-07-06 20:28:31
【问题描述】:

当我进行 JQuery 调用时,我得到一个身份验证失败响应:

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

jQuery 调用:

$(document).ready(function () {
    //Handle the change event for the drop down list
    $("#ddRegions").change(function () {
        //create the ajax request
        $.ajax({
            type: "POST", //HTTP method
            url: '<%= ResolveUrl("WebForm2.aspx/getLocations")%>', //page/method name
            data: "{}", //json to represent argument
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) { //handle the callback to handle response                
                //request was successful. so Retrieve the values in the response.
                alert(msg.toSource());
            }
        });
    });
});

网络方法:

public static string getLocations() {
    System.Diagnostics.Debug.WriteLine("Getting Locations.");
    return "{region:auckland, city:auckland}";
}

我在 web.config 中添加了以下内容:

<authorization>
    <allow users="*" />
</authorization>
<authentication mode="None" />

我尝试在RouteConfig.cs 中将AutoRedirectMode 设置为Off。这会停止错误,但仍然不会调用 web 方法。有什么建议吗?

【问题讨论】:

  • 您是否尝试过使用 $.support.cors = true;在 jquery 中启用跨源这是出于安全目的限制浏览器?
  • 当你说它永远不会被调用时,浏览器会发送请求吗?如果可以,您能否使用 Fiddler 或 Google Chrome 开发者工具显示响应和请求?
  • 这对您有帮助吗? forums.asp.net/t/…
  • 这甚至是先回发吗?
  • dataType: 'json' 强制 jquery 自动解析响应数据。但是getLocations() 方法返回无效的 json。应该是:{"region":"auckland", "city":"auckland"}。双引号对于JSON.parse() 非常重要。

标签: c# jquery asp.net ajax webmethod


【解决方案1】:

通过在 App_Start/RouteConfig.cs 中将 AutoDirectMode 设置为 Off 解决

settings.AutoRedirectMode = RedirectMode.Off;

并将 ScriptManager 添加到 EnablePageMethods 设置为“true”的 aspx 页面:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 2016-09-05
    • 2014-05-25
    • 2016-01-09
    • 2018-11-02
    • 2015-12-01
    • 2012-06-17
    • 1970-01-01
    相关资源
    最近更新 更多