Daniel Cardenas Daniel Cardenas - 10 months ago 119
Ajax Question

ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

Been stuck with this for hours

{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

I'm trying to call this WebMethod in my ASP.Net Webform

public static string GetClients(string searchTerm, int pageIndex)
string query = "[GetClients_Pager]";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
cmd.Parameters.AddWithValue("@PageSize", PageSize);
cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd, pageIndex).GetXml();

From this jquery.ajax

function GetClients(pageIndex) {
type: "POST",
url: "ConsultaPedidos.aspx/GetClients",
data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
error: function (response) {

But I always get this error:


Weird thing is that this used to work until I start authenticating users

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

Any ideas?

Answer Source

Problem solved

This was driving me crazy.

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;


settings.AutoRedirectMode = RedirectMode.Off;

(Or just comment the line)

Also if friendly URLs are enabled you need to change

url: "ConsultaPedidos.aspx/GetClients",


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

Hope this help somebody else