Getting "401 Unauthorized" error consistently with jquery call to webmethod
Asked Answered
G

3

8

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.

Your insight is appreciated!

Call to js function the invokes the jquery call

button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";

JavaScript function that makes the jquery call

function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;

//Create list of parameters in the form:  
//{"paramName1":"paramValue1","paramName2":"paramValue2"}  
var paramList = '';
if (paramArray.length > 0) {
    for (var i = 0; i < paramArray.length; i += 2) {
        if (paramList.length > 0) paramList += ',';
        paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
    }
}
paramList = '{' + paramList + '}';

//Call the page method
$.ajax({
    type: "POST",
    url: pagePath + "/" + fn,
    contentType: "application/json; charset=utf-8",
    data: paramList,
    timeout: 10000,
    dataType: "json",
    success: function(result) { alert('Overjoyed'); },
    error: function(result) { alert('No joy'); }
});
}

Web method in page

    public partial class WebLayout : System.Web.UI.Page
{

    [WebMethod()]
    public static int TestNoParams()
    {
        return 1;
    }

    [WebMethod()]
    public static string TestWithParams(string a, int b)
    {
        return a + b.ToString();
    }
...

Response as seen in Firebug console

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

and

"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams

I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.

Here are some other potentially useful tidbits that may impact your diagnosis:

  • Webmethods in codebehind
  • Using Sitecore CMS (Does not seem to intefere, never know)
  • IIS7
  • .NET 3.5
  • jQuery 1.3.2

I look forward to your insights and direction--thank you!

Gan answered 19/2, 2010 at 16:27 Comment(0)
G
6

Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.

Gan answered 22/2, 2010 at 8:18 Comment(4)
Hi CareMatch - I'm guessing that I have the same problem that you described above. Can you please let me know what you did exactly to solve this problem.Hiss
Added ScricptResource.axd to IgnoreUrlPrefixs in web.config.Hiss
Hey CareMatch - I'm running into the same problem, could you provide a list of what you've done to get it working, please?Onagraceous
The answers a bit sketchy, but it's sent me in the right direction.Mersey
S
2

The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.

First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.

If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search

Steffin answered 19/2, 2010 at 18:37 Comment(1)
I suspect that Sitecore CMS may at fault (it intercepts the requests), as I built a single aspx page (webmethods in codebehind, jquery, etc.)--with some fiddling, it worked! On the right track, I again moved this working code to my project using the CMS. I was able to create CMS page that would not be processed by Sitecore (IgnoreUrlPrefixes in web.config), so now I am encountering an Internal Server Error--any clues, as this error provides few indications where to look.Gan
D
0

What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.

If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.

Post more settings if the problem is not resolved. Hope this helps.

Doorjamb answered 19/2, 2010 at 17:42 Comment(1)
I am using Forms authentication, the user is logged in, but as I stated above, it appears that on-the-fly creation of friendly URLs by Sitecore may be the issue, now with an ASPX outside Sitecore processing, I am getting an Internal Server Error--so more diagnosing is necessary.Gan

© 2022 - 2024 — McMap. All rights reserved.