简体   繁体   English

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

[英]ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

Been stuck with this for hours坚持了几个小时

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

I'm trying to call this WebMethod in my ASP.Net Webform我试图在我的 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();
}

From this jquery.ajax从这个 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);
            }
    });
}

But I always get this error:但我总是收到这个错误:

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

Weird thing is that this used to work until I start authenticating users奇怪的是,在我开始对用户进行身份验证之前,这曾经有效

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

Any ideas?有任何想法吗?

Problem solved问题解决了

This was driving me crazy.这让我发疯。

Inside ~/App_Start/RouteConfig.cs change:~/App_Start/RouteConfig.cs 里面改变:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:到:

settings.AutoRedirectMode = RedirectMode.Off;

(Or just comment the line) (或者只是注释该行)

Also if friendly URLs are enabled you need to change此外,如果启用了友好 URL,您需要更改

url: "ConsultaPedidos.aspx/GetClients",

To:到:

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

Hope this help somebody else希望这对其他人有帮助

Inside ~/App_Start/RouteConfig.cs change里面~/App_Start/RouteConfig.cs改变

settings.AutoRedirectMode = RedirectMode.Permanent;

to

settings.AutoRedirectMode = RedirectMode.Off;

401 Unauthorised means that: 401未授权意味着:

  • User authentication hasn't been provided or未提供用户身份验证
  • It was provided but failed authentication tests已提供但未通过身份验证测试

This corroborates with what you've said about adding authentication, it's clearly covering this method too.这证实了您所说的添加身份验证的内容,它显然也涵盖了此方法。

Therefore do you want access to this method to be public or not?因此,您是否希望对该方法的访问是公开的?

Public :公众

  • You need to remove authentication from this method.您需要从此方法中删除身份验证。

To allow access to public resources (such as this webmethod) you simply place this in the config file in the same directory:要允许访问公共资源(例如此 webmethod),您只需将其放在同一目录的配置文件中:

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

if you put above tag then it will give access right to all kind of users to all resources.如果你把标签放在上面,那么它将为所有类型的用户提供对所有资源的访问权限。 so instead of that you can add below tag to give authorization to the web service所以你可以添加下面的标签来授权给网络服务

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

Private :私人

  • You need to ensure authentication is being sent across the line (using Fiddler to check for the cookie), and ensure it's is passing asp.net authentication.您需要确保在线发送身份验证(使用Fiddler检查 cookie),并确保它通过 asp.net 身份验证。

You have to comment out only in ~/App_Start/RouteConfig.cs你只需要在 ~/App_Start/RouteConfig.cs 中注释掉

  // settings.AutoRedirectMode = RedirectMode.Permanent;

             (Or do this)

    settings.AutoRedirectMode = RedirectMode.Off;

There is nothing to do with Authentication in Web.config file.与 Web.config 文件中的身份验证无关。

Not an expert but have you tried by putting <allow users="*"/> in the config file?不是专家,但您是否尝试过将<allow users="*"/>放在配置文件中? Your request should be using a GET method and not a POST (used to create).您的请求应该使用 GET 方法而不是 POST(用于创建)。

EDIT: It seems that you are using a SOAP method, which can't be called from clientside, you should use a RESFUL service.编辑:您似乎正在使用无法从客户端调用的 SOAP 方法,您应该使用 RESFUL 服务。

I found this question trying to solve the same problem, the way I solved is not seen here so I post to someone stuck in the same bottleneck:我发现这个问题试图解决同样的问题,这里没有看到我解决的方法,所以我发布给陷入相同瓶颈的人:

Try in your method use the EnableSession = true in your WebMethod attribute尝试在您的方法中使用EnableSession = true在您的 WebMethod 属性中

like喜欢

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

with this is solved my 401 error.这样就解决了我的 401 错误。 Hope be helpful.希望有所帮助。

In my case, I was adding the WebMethod to a control on the form.就我而言,我将 WebMethod 添加到表单上的控件中。 It needs to be added to the page itself.它需要添加到页面本身。

I faced the same problem and firstly tried the solution which is available and it does work.我遇到了同样的问题,首先尝试了可用的解决方案,它确实有效。 However I realised if I create a new web-service and add the relevent code in the App_Code folder of the web-service file then I don't get any errors.但是我意识到如果我创建一个新的web-service并在web-service文件的App_Code文件夹中添加相关代码,那么我不会收到任何错误。

I know you got your answer accepted.我知道你的回答被接受了。 It actually happens while creating a Web Form application and not changing the Authentication to No Authentication .它实际上是在创建 Web 窗体应用程序并且未将Authentication更改为No Authentication

The default authentication we see as Authentication: Individual User Account我们看到的默认身份验证为Authentication: Individual User Account

The error will not come if we change to Authentication: No Authentication如果我们更改为Authentication: No Authentication就不会出现错误

我的网站正在使用 ASP.NET 表单身份验证,我通过反复试验发现,只有在.asmx页面上调用 Web 方法并使用contentType: "application/x-www-form-urlencoded"dataType: "xml"

In my case the problem was in URL that calls Ajax.asmx this URL was not correct according to a webserver setup, eg "/qa/Handlers/AjaxLib.asmx/" worked for me instead of "/Handlers/AjaxLib.asmx/" (works fine on PROD servers in my particular situation):在我的情况下,问题出在调用 Ajax.asmx 的 URL 中,根据网络服务器设置,此 URL 不正确,例如"/qa/Handlers/AjaxLib.asmx/"对我"/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 () {

My AJAX was then called out of scope of my IIS virtual application directory "qa", hence Authorization error occured ({"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}).然后我的 AJAX 被调用超出了我的 IIS 虚拟应用程序目录“qa”的范围,因此发生了授权错误({"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}).

To allow this Web Service to be called from script, using ASP.NET AJAX.允许使用 ASP.NET AJAX 从脚本调用此 Web 服务。 Add the following attribute to the class将以下属性添加到类

[System.Web.Script.Services.ScriptService]

I faced similar issue and the adding this attribute resolved it.我遇到了类似的问题,添加此属性解决了它。

For me, I had an invalid "data:" parameter in my JQuery Ajax call.对我来说,我的 JQuery Ajax 调用中有一个无效的“数据:”参数。 But rather than either .NET or JQuery complaining about the the parameter values, I was (misleadingly in my opinion) getting the 401 Unauthorized error.但不是 .NET 或 JQuery 抱怨参数值,而是(在我看来是误导)收到 401 Unauthorized 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM