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
DDDOriginal
2025-01-04 08:31:34561browse

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();
}

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",
        // ...
    });
}

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>

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;

      to:

      settings.AutoRedirectMode = RedirectMode.Off;
  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"
      • To:

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

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:
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