ASP.NET使用jQuery AJAX调用WebMethod“401(未经授权)”

问题描述 投票:33回答:10

被困这几个小时了

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

我试图在我的ASP.Net Webform中调用这个WebMethod

[WebMethod]
public static string GetClients(string searchTerm, int pageIndex)
{
    string query = "[GetClients_Pager]";
    SqlCommand cmd = new SqlCommand(query);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
    cmd.Parameters.AddWithValue("@PageSize", PageSize);
    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
    return GetData(cmd, pageIndex).GetXml();
}

从这个jquery.ajax

function GetClients(pageIndex) {
    $.ajax({
        type: "POST",
        url: "ConsultaPedidos.aspx/GetClients",
        data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
    });
}

但我总是得到这个错误:

POST http://localhost:64365/ConsultaPedidos.aspx/GetClients 401(未经授权)

奇怪的是,这开始工作直到我开始验证用户

<system.web>
...
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="/Dashboard" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
...
</system.web>

有任何想法吗?

c# jquery asp.net ajax webmethod
10个回答
147
投票

问题解决了

这让我发疯了。

里面〜/ App_Start / RouteConfig.cs改变:

settings.AutoRedirectMode = RedirectMode.Permanent;

至:

settings.AutoRedirectMode = RedirectMode.Off;

(或者只是评论一下)

此外,如果启用友好URL,则需要更改

url: "ConsultaPedidos.aspx/GetClients",

至:

url: '<%= ResolveUrl("ConsultaPedidos.aspx/GetClients") %>',

希望这有助于其他人


0
投票

在我的情况下,问题是在URL中调用Ajax.asmx,根据网络服务器设置,此URL不正确,例如"/qa/Handlers/AjaxLib.asmx/"为我工作而不是"/Handlers/AjaxLib.asmx/"(在我的特殊情况下在PROD服务器上正常工作):

  $.ajax({
  url: '/qa/Handlers/AjaxLib.asmx/' + action,
  type: "POST",
  async: false,
  data: data,
  contentType: "application/json; charset=utf-8",
  success: function () {

然后我的AJAX被调出我的IIS虚拟应用程序目录“qa”的范围,因此授权错误发生了({"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}).


11
投票

里面~/App_Start/RouteConfig.cs改变

settings.AutoRedirectMode = RedirectMode.Permanent;

settings.AutoRedirectMode = RedirectMode.Off;

5
投票

401 Unauthorized意味着:

  • 尚未提供用户身份验证或
  • 提供但验证测试失败

这证实了你所说的关于添加身份验证的内容,它显然也涵盖了这种方法。

因此,您是否希望访问此方法是否公开?

上市:

  • 您需要从此方法中删除身份验证。

要允许访问公共资源(例如此webmethod),只需将其放在同一目录中的配置文件中:

 <authorization>
        <allow users="*" /> 
 </authorization>

如果您将上面的标记放在上面,那么它将为所有资源提供对所有类型用户的访问权限。因此,您可以添加以下标记来授予Web服务授权

<location path="YourWebServiceName.asmx">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>

私人的:

  • 您需要确保通过线路发送身份验证(使用Fiddler检查cookie),并确保它正在通过asp.net身份验证。

2
投票

不是专家,但你尝试将<allow users="*"/>放在配置文件中吗?您的请求应该使用GET方法而不是POST(用于创建)。

编辑:您似乎使用的是SOAP方法,无法从客户端调用,您应该使用RESFUL服务。


2
投票

我发现这个问题试图解决同样的问题,我解决的方式在这里没有看到所以我发布给陷入同一瓶颈的人:

尝试使用您的方法在WebMethod属性中使用EnableSession = true

喜欢

[WebMethod(EnableSession = true)]
public static string MyMethod()
{
    return "no me rindo hdp";
}

用这个解决了我的401错误。希望有所帮助。


1
投票

在我的例子中,我将WebMethod添加到表单上的控件。它需要添加到页面本身。


0
投票

我遇到了同样的问题,并首先尝试了可用的解决方案,它确实有效。但是我意识到如果我创建一个新的web-service并在App_Code文件的web-service文件夹中添加相关代码,那么我没有得到任何错误。


0
投票

我知道你接受了你的回答。它实际上发生在创建Web窗体应用程序而不是将Authentication更改为No Authentication时。

我们看到的默认身份验证为Authentication: Individual User Account

如果我们改为Authentication: No Authentication,错误就不会出现


0
投票

我的网站使用的是ASP.NET表单身份验证,我通过反复试验得出结果,如果我在.asmx页面上调用了一个web方法并使用contentType: "application/x-www-form-urlencoded"dataType: "xml",我只能使用它

© www.soinside.com 2019 - 2024. All rights reserved.