Mike
Mike

Reputation: 21

How to add custom header to ASMX web service call using jquery?

I have a web service with the following contract:

POST /Service/service.asmx HTTP/1.1
Host: xxx.xxx.xxx
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "xxx.xxx.xxx/Service/Method"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <Request xmlns="xxx.xxx.xxx/Service/">
      <transactiontype>string</transactiontype>
      <username>string</username>
      <password>string</password>
    </Request>
  </soap:Header>
  <soap:Body>
    <Method xmlns="xxx.xxx.xxx/Service/">
      <xml>xml</xml>
    </Method>
  </soap:Body>
</soap:Envelope>

And I am trying to call the service using jquery. This is my code:

$.ajax({
    url: serverUrl + 'Method',
    type: "POST",
    dataType: "xml",
    data: { xml: "xml" },
    beforeSend: function (req) {
        req.setRequestHeader('Header', '<Request xmlns="xxx.xxx.xxx/Service/">'
                            +'<transactiontype>4</transactiontype>'
                            +'<agencyName>name</agencyName>'
                            +'<username>user</username>'
                            +'<password>pass</password>'
                            +'</Request>');                    
    },
    success: function (data) {
        alert(data.text);
    },
    error: function (request, status, errorThrown) {
        alert(status);
    }
});

However, the header content is not passed to the web service? How would I go about passing the header credentials to my web service call?

Upvotes: 2

Views: 3971

Answers (1)

user166390
user166390

Reputation:

soap:Header is an XML element inside the XML/SOAP data "payload". This is different than an HTTP headers. In the contract, SOAPAction (along with Content-Length, etc) is an HTTP header.

XmlHttpRequest.setRequestHeader is used for specifying HTTP headers. It has nothing to do with anything inside the XML (directly).

The first answer at Simplest SOAP example should give an example of how to make a SOAP request. Note:

xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
...
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
    '<soap:Envelope...' + etc;
xmlhttp.send(xml)

It is the XML which contains soap:Envelope and the child elements soap:Header and soap:Body.

Happy coding.

Upvotes: 1

Related Questions