Home >Backend Development >C++ >Why Am I Getting a 401 Unauthorized Error When Calling an ASP.NET WebMethod with jQuery AJAX?

Why Am I Getting a 401 Unauthorized Error When Calling an ASP.NET WebMethod with jQuery AJAX?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 13:28:41387browse

Why Am I Getting a 401 Unauthorized Error When Calling an ASP.NET WebMethod with jQuery AJAX?

Unauthorized WebMethod Call with ASP.NET and jQuery AJAX

Issue Description

Users face authorization errors (401) when attempting to call a WebMethod in ASP.NET using jQuery AJAX. The error message typically reads as "Authentication failed."

Background

The WebMethod is declared in a WebForm as:

[WebMethod]
public static string GetClients(string searchTerm, int pageIndex) { /*...*/ }

However, upon calling the WebMethod with:

$.ajax({ /*...*/
    url: "ConsultaPedidos.aspx/GetClients",
    /*...*/
});

the browser responds with a 401 Unauthorized error.

Solution

The solution to this issue involves disabling the automatic redirection mechanism in ASP.NET:

  1. Navigate to ~/App_Start/RouteConfig.cs.
  2. Locate the line:

    settings.AutoRedirectMode = RedirectMode.Permanent;
  3. Change it to:

    settings.AutoRedirectMode = RedirectMode.Off;

    Alternatively, you can comment out the line.

Additional Modification:

If friendly URLs are enabled in the application, you must also change:

url: "ConsultaPedidos.aspx/GetClients",

to:

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

Explanation:

By default, ASP.NET automatically redirects unauthorized requests to the login page. Disabling this behavior allows the WebMethod call to proceed.

The above is the detailed content of Why Am I Getting a 401 Unauthorized Error When Calling an ASP.NET WebMethod with jQuery AJAX?. 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