locked
how to add soap header from jquery ajax call? RRS feed

  • Question

  • User-285183832 posted
    //I've web service and used soap header authentication .which i can call from page behind but i need  to call it from jquery. My code is ...
    
    
           
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Services;
        
        /// <summary>
        /// Summary description for test
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
         [System.Web.Script.Services.ScriptService]
        public class test : System.Web.Services.WebService {
           
            public test () {
        
                //Uncomment the following line if using designed components 
                //InitializeComponent(); 
            }
        
            public SecuredWebServiceHeader SoapHeader;
        
            [WebMethod]
            [System.Web.Services.Protocols.SoapHeader("SoapHeader")]
            public string AuthenticateUser()
            {
                if (SoapHeader == null)
                    return "Please provide a Username and Password";
                if (string.IsNullOrEmpty(SoapHeader.Username) || string.IsNullOrEmpty(SoapHeader.Password))
                    return "Please provide a Username and Password";
        
                // Are the credentials valid?
                if (!IsUserValid(SoapHeader.Username, SoapHeader.Password))
                    return "Invalid Username or Password";
        
                // Create and store the AuthenticatedToken before returning it
                string token = Guid.NewGuid().ToString();
                HttpRuntime.Cache.Add(
                    token,
                    SoapHeader.Username,
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    TimeSpan.FromMinutes(60),
                    System.Web.Caching.CacheItemPriority.NotRemovable,
                    null);
        
                return token;
            }
        
        
            private bool IsUserValid(string Username, string Password)
            {
                // Ask the SQL Memebership to verify the credentials for us
                //return System.Web.Security.Membership.ValidateUser(Username, Password);
        
                if (Username.ToLower() == "username" && Password.ToLower() == "password")
                    return true;
                else
                {
                    return false;
                }
            }
        
        
            private bool IsUserValid(SecuredWebServiceHeader SoapHeader)
            {
                if (SoapHeader == null)
                    return false;
        
                // Does the token exists in our Cache?
                if (!string.IsNullOrEmpty(SoapHeader.AuthenticatedToken))
                    return (HttpRuntime.Cache[SoapHeader.AuthenticatedToken] != null);
        
                return false;
            }
           
            [WebMethod]
            [System.Web.Services.Protocols.SoapHeader("SoapHeader")]
            public string HelloWorld()
            {
                if (!IsUserValid(SoapHeader))
                    return "Please call AuthenitcateUser() first.";
        
                return "Hello " +HttpRuntime.Cache[SoapHeader.AuthenticatedToken];
            }
            
        }
        
        public class SecuredWebServiceHeader : System.Web.Services.Protocols.SoapHeader
        {
            public string Username;
            public string Password;
            public string AuthenticatedToken;
        }
    
    
    
    
     
    //inside page srcipt
         var soapMessage2 =
                '<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:Body> \
                <SecuredWebServiceHeader  xmlns="http://tempuri.org/"> \
                <Username>username</Username> \
                <Password>password</Password> \
                <AuthenticatedToken></AuthenticatedToken> \
                </SecuredWebServiceHeader> \
                </soap:Body> \
                </soap:Envelope>';
        
          $.ajax({
                    url: "http://localhost:56237/Jquery_Auth_WebService/test.asmx/HelloWorld",
                    type: "POST",
                    dataType: "xml",
                    data: soapMessage2,
                    complete: function(){},
                    contentType: "text/xml; charset=\"utf-8\""
                });
    //when request arrives to server soapheader is always null why?
    
    //So  How do i send soapheader with information
    

    Wednesday, April 18, 2012 7:51 AM

Answers

  • User-742633084 posted

    Thanks for reply bakamaru,

    Well, I've performed a simple test with the following webservice and JQuery based script code:

    #web service code

    [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        public class WebService4JQuery : System.Web.Services.WebService
        {
            
            public TestHeader THeader;
    
            [WebMethod]
            [SoapHeader("THeader")]
            public string TestSoapHeader()
            {
    
                return "THeader Value: " + THeader.HeaderData;
            }
        }
    
        public class TestHeader : SoapHeader
        {
            public string HeaderData { get; set; }
        }
    


    #JQuery code in the webform page

    <script type="text/javascript">
    
            function CallWebMethodWithHeader() {
    
                var soapXML = 
                "<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>" +
                    "<TestHeader xmlns='http://tempuri.org/'>" +
                        "<HeaderData>111111111111</HeaderData>" +
                    "</TestHeader>" +
                "</soap:Header>" +
                "<soap:Body>" +
                    "<TestSoapHeader xmlns='http://tempuri.org/' />" +
                "</soap:Body>" +
                "</soap:Envelope>";
            
                $.ajax({
                    url: "WebService4JQuery.asmx?op=TestSoapHeader",
                    type: "POST",
                    dataType: "xml",
                    contentType:"text/xml; charset=utf-8",
                    data: soapXML,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/TestSoapHeader');
    
                    },
    
                    success: function (data) {
                        alert("webmethod call success");
                    },
                    error: function (err) {
                        alert("webmethod call failed");
                    }
    
                });
     
            }
        </script>


    the difference I can see is that you haven't specified the "Content-Type" and "SOAPAction" HTTP header. You can try adjust your script code to see if it works.

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 20, 2012 1:23 AM

All replies

  • User1849990362 posted

    Try using "beforeSend"

    $.ajax({
                    url: "http://localhost:56237/Jquery_Auth_WebService/test.asmx/HelloWorld",
                    type: "POST",
                    dataType: "xml",
                    data: soapMessage2,
                    beforeSend: function(xhr){xhr.setRequestHeader('X-Test- 
                    Header', 'test-value');},
                    complete: function(){},
                    contentType: "text/xml; charset=\"utf-8\""
                });
    


    Refer this thread for more informaion.

    http://stackoverflow.com/questions/10081728/add-request-header-on-backbone

    Wednesday, April 18, 2012 8:22 AM
  • User-285183832 posted

    I've tried that one too but not working this is how i send the soap header

    var soapMessage2 =
              '<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:Body> \
              <SecuredWebServiceHeader xmlns="http://tempuri.org/"> \
              <Username>username</Username> \
              <Password>password</Password> \
              <AuthenticatedToken></AuthenticatedToken> \
              </SecuredWebServiceHeader> \
              </soap:Body> \
              </soap:Envelope>';
    $.ajax({
                url: "http://localhost:56237/Jquery_Auth_WebService/test.asmx/HelloWorld",
                type: "POST",
                dataType: "xml",
                data: soapMessage2,
      beforeSend: function(xhr){
    xhr.setRequestHeader('SecuredWebServiceHeader', soapMessage2 );},

                complete: function(){}
              
            });

    Thursday, April 19, 2012 12:32 AM
  • User-742633084 posted

    Hi bakamaru,

    Your webservice's webmethod has defined a custom soapheader, then the soapheader should be sent within the SOAP XML request and inside the <soap:Envelope> element. For example:

    <?xml version="1.0"?>
     <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
       <soap:Header>
      <!-- here to put your custom soap headers -->
       </soap:Header>
       <soap:Body>
         <!-- soap body elements -->
       </soap:Body>
     </soap:Envelope>


    #SOAP format
    http://en.wikipedia.org/wiki/SOAP

    Also, I suggest you first create a .NET based client (via Visual Studio "Add WebReference") and call the service. And you can use fiddler to captur the HTTP request(that contains the complete SOAP XML message) so as to verify the correct format expected by the server:

    #Fiddler Web Debugger
    http://www.fiddler2.com/fiddler2/

    BTW, for the $.ajax JQuery api, the "message header" you set via "BeforeSend" handler is used for setting custom HTTP header (not SOAP header). Your custom soap header should be set in your message content( your first jQuery call should be correct, but you put the soapheader at the wrong place in the request XML content).

     

     

    Thursday, April 19, 2012 3:16 AM
  • User-285183832 posted

    still not working can you provide with sample with coding

    Thursday, April 19, 2012 6:46 AM
  • User-742633084 posted

    Thanks for reply bakamaru,

    Well, I've performed a simple test with the following webservice and JQuery based script code:

    #web service code

    [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        public class WebService4JQuery : System.Web.Services.WebService
        {
            
            public TestHeader THeader;
    
            [WebMethod]
            [SoapHeader("THeader")]
            public string TestSoapHeader()
            {
    
                return "THeader Value: " + THeader.HeaderData;
            }
        }
    
        public class TestHeader : SoapHeader
        {
            public string HeaderData { get; set; }
        }
    


    #JQuery code in the webform page

    <script type="text/javascript">
    
            function CallWebMethodWithHeader() {
    
                var soapXML = 
                "<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>" +
                    "<TestHeader xmlns='http://tempuri.org/'>" +
                        "<HeaderData>111111111111</HeaderData>" +
                    "</TestHeader>" +
                "</soap:Header>" +
                "<soap:Body>" +
                    "<TestSoapHeader xmlns='http://tempuri.org/' />" +
                "</soap:Body>" +
                "</soap:Envelope>";
            
                $.ajax({
                    url: "WebService4JQuery.asmx?op=TestSoapHeader",
                    type: "POST",
                    dataType: "xml",
                    contentType:"text/xml; charset=utf-8",
                    data: soapXML,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/TestSoapHeader');
    
                    },
    
                    success: function (data) {
                        alert("webmethod call success");
                    },
                    error: function (err) {
                        alert("webmethod call failed");
                    }
    
                });
     
            }
        </script>


    the difference I can see is that you haven't specified the "Content-Type" and "SOAPAction" HTTP header. You can try adjust your script code to see if it works.

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 20, 2012 1:23 AM
  • User-285183832 posted

    THANKs Steven now its working

    Monday, April 23, 2012 12:12 AM
  • User-1778014093 posted

    hi bakamaru,

    i am very curious to see your code, as i have implmented the same service calls. Can you possibly share that?

    Tuesday, July 23, 2013 8:53 PM