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

Solution 1:

Problem solved

This was driving me crazy.

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

(Or just comment the line)

Also if friendly URLs are enabled you need to change

url: "ConsultaPedidos.aspx/GetClients",

To:

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

Hope this help somebody else

Solution 2:

Inside ~/App_Start/RouteConfig.cs change

settings.AutoRedirectMode = RedirectMode.Permanent;

to

settings.AutoRedirectMode = RedirectMode.Off;

Solution 3:

401 Unauthorised means that:

  • User authentication hasn't been provided or
  • It was provided but failed authentication tests

This corroborates with what you've said about adding authentication, it's clearly covering this method too.

Therefore do you want access to this method to be public or not?

Public:

  • You need to remove authentication from this method.

To allow access to public resources (such as this webmethod) you simply place this in the config file in the same directory:

 <authorization>
        <allow users="*" /> 
 </authorization>

if you put above tag then it will give access right to all kind of users to all resources. so instead of that you can add below tag to give authorization to the web service

<location path="YourWebServiceName.asmx">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>

Private:

  • You need to ensure authentication is being sent across the line (using Fiddler to check for the cookie), and ensure it's is passing asp.net authentication.