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
Release: 2025-01-05 13:28:41
Original
386 people have browsed it

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) { /*...*/ }
Copy after login

However, upon calling the WebMethod with:

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

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;
    Copy after login
  3. Change it to:

    settings.AutoRedirectMode = RedirectMode.Off;
    Copy after login

    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",
Copy after login

to:

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

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template