使用$.ajax调用Web方法时出现身份验证失败错误

6
当我进行 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());
            }
        });
    });
});

网络方法(Web Method):
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方法仍然不会被调用。有任何建议吗?


1
你尝试过在jQuery中使用$.support.cors = true;来启用跨域吗?这是出于安全目的,浏览器对此进行了限制。 - Sunil Kumar
dataType: 'json' 强制 jQuery 自动解析响应数据。但是 getLocations() 方法返回无效的 JSON。它应该是:{"region":"auckland", "city":"auckland"}。双引号对于 JSON.parse() 非常重要。 - marcel
你确定你的调用没有返回值吗?(我没有看到toSource()的定义。尝试将成功回调更改为alert(msg.d))。另外,你的服务器端函数上面如何使用[WebMethod]装饰器?如果其他方法都失败了,也可以尝试暂时禁用RegisterRoutes。 - potatopeelings
然而,使用AutoRedirectMode.Off时,我收到了响应中的消息:“未知的Web方法getLocations。” - Aaz
仅供参考:http://www.codeproject.com/Articles/655086/Handling-authentication-specific-issues-for-AJAX-c - Mani
显示剩余4条评论
1个回答

4

通过在 App_Start/RouteConfig.cs 中将 AutoDirectMode 设置为 Off 来解决该问题。

settings.AutoRedirectMode = RedirectMode.Off;

同时,在具有“EnablePageMethods”设置为“true”的aspx页面中添加ScriptManager:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接