Home > Backend Development > C++ > Why Does My jQuery AJAX Call to an ASP.NET WebMethod Result in a '401 Unauthorized' Error?

Why Does My jQuery AJAX Call to an ASP.NET WebMethod Result in a '401 Unauthorized' Error?

DDD
Release: 2025-01-04 08:31:34
Original
557 people have browsed it

Why Does My jQuery AJAX Call to an ASP.NET WebMethod Result in a

ASP.NET: WebMethod with jQuery AJAX Returns "401 Unauthorized" Error

When attempting to call a WebMethod in an ASP.NET WebForm using jQuery AJAX, an "401 (Unauthorized)" error may be encountered. This issue arises due to authentication settings in the web.config file.

The WebMethod is configured as follows:

[WebMethod]
public static string GetClients(string searchTerm, int pageIndex)
{
    // ...
    return GetData(cmd, pageIndex).GetXml();
}
Copy after login

And the jQuery AJAX call is made from:

function GetClients(pageIndex) {
    $.ajax({
        type: "POST",
        url: "ConsultaPedidos.aspx/GetClients",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        // ...
    });
}
Copy after login

However, after enabling user authentication in the web.config file:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="/Dashboard" />
</authentication>
<authorization>
    <deny users="?" />
</authorization>
Copy after login

The AJAX call fails with the aforementioned error.

Solution:

To resolve this issue, two modifications are necessary:

  1. Disable ASP.NET Autoname Redirects:

    • Open the RouteConfig.cs file in the App_Start folder.
    • Change the following line:

      settings.AutoRedirectMode = RedirectMode.Permanent;
      Copy after login

      to:

      settings.AutoRedirectMode = RedirectMode.Off;
      Copy after login
  2. Fix Friendly URL Path:

    • For websites that enable friendly URLs, the URL in the jQuery AJAX call must be modified:

      • Change:

        url: "ConsultaPedidos.aspx/GetClients"
        Copy after login
      • To:

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

These adjustments will enable the jQuery AJAX call to access the WebMethod without triggering the "401 Unauthorized" error.

The above is the detailed content of Why Does My jQuery AJAX Call to an ASP.NET WebMethod Result in a '401 Unauthorized' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template