2

I am trying to make a call to wcf function using ajax as below:

$.ajax({
        url:http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?',
        dataType: 'json',
        beforeSend : function(xhr) {
            xhr.setRequestHeader("Authorization", "BasicAuthTest");
        },
        success: function(trackingData) {
            alert("success");
        }
    });

WCF code is beaking and is receving the request

public class CustomUserNameValidatorBasic : ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            try
            {
                var msg = operationContext.RequestContext.RequestMessage;

                // If user requests standart help-page then ignore authentication check.
                if (msg.Properties.ContainsKey("HttpOperationName") && msg.Properties["HttpOperationName"].ToString() == "HelpPageInvoke")
                {

                    return base.CheckAccessCore(operationContext);
                }

                var httpRequestHeaders = ((HttpRequestMessageProperty) msg.Properties[HttpRequestMessageProperty.Name]).Headers;

                // Is Authorization-header contained in http-headers?
                if (!httpRequestHeaders.AllKeys.Contains(HttpRequestHeader.Authorization.ToString()))
                {
                    //code returns here
                    return false;
                }

                    return false;

            }
            catch (Exception e)
            {
                return false;
            }

        }
    }

As shown "Authorization" header is not included in req header array

enter image description here

In Firebug Under Request Headers for ajax reqeuest:

Request Headersview source Accept / Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5 Cache-Control max-age=0
Connection keep-alive Host test.proxyU.com If-Modified-Since Wed, 21 Mar 2012 19:46:56 GMT If-None-Match "e0818-17278-4bbc60dc86c00"
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0)
Gecko/20100101 Firefox/16.0

Update: Considering Answer below I have tried 3 Methods as below none of them adds the header. All call wcf correctly but `Authorization' header is just not in the request. And if I watch the http request the header looks very much like the screen shot I posted above

Method 1

$.ajax({
        url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
        beforeSend: function(xhr){xhr.setRequestHeader("Authorization", "BasicAuthTest");},
        success: function(trackingData) {
            alert("success");
        }
    });

Method 2

$.ajax({
        url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
        headers: {"Authorization": "BasicAuthTest"},
        success: function(trackingData) {
            alert("success");
        }
    });

Method 3

$.ajax({
        url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
        beforeSend : function(xhr, settings) {
            $.extend(settings, { headers : { "Authorization" : "BasicAuthTest" } });
        },
        success: function(trackingData) {
            alert("success");
        }
    });
6
  • Use developer tools in your browser (typically F12) and check if header added to request. Commented Feb 7, 2013 at 21:05
  • I updated the question with headers Commented Feb 7, 2013 at 21:15
  • @jaminator what version of jquery? Commented Feb 8, 2013 at 16:18
  • @drch 1.7.2, I just noticed in chrome debugger that when i use Method 3 instead of adding a whole new header I see: Access-Control-Request-Headers:accept, authorization, origin Commented Feb 8, 2013 at 16:21
  • when I call this wcf from asp.net website using c# i see a complete new header entry Authorization being entered and it works fine. But from javascript/jquery it appears to be adding the header inside Access-Control-Request-Headers Commented Feb 8, 2013 at 16:24

2 Answers 2

1

From documentation on setRequestHeader()

You must call setRequestHeader() after open(), but before send().

Looking at the jQuery source, open() is called on send() so you can't set the headers via the xhr object in beforeSend()

The jQuery documentation on $.ajax regarding headers says:

This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

So you can update the headers in beforeSend(xhr, settings) via the settings object and jQuery will pick them up.

$.ajax({
    url:http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?',
    dataType: 'json',
    beforeSend : function(xhr, settings) {
        $.extend(settings, { headers : { "Authorization", "BasicAuthTest" } }
    },
    success: function(trackingData) {
        alert("success");
    }
});

Alternatively, you can pass in a headers parameter into your $.ajax() call:

$.ajax({
    url: ...,
    headers : { "Authorization", "BasicAuthTest" }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Updated question considering your answer
0

Yes it was a cross domain issue, I used this visual studio project template and it made things fairly easy. There is a working example in there too for http get from the service

2 Comments

Can you explain what you did to fix this on localhost? I have the exact same problem.
just use the project template linked above, it has working example in it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.