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:
Disable ASP.NET Autoname Redirects:
Change the following line:
settings.AutoRedirectMode = RedirectMode.Permanent;
to:
settings.AutoRedirectMode = RedirectMode.Off;
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!