Sending SOAP message with C# Help Needed

后端 未结 4 1180
我寻月下人不归
我寻月下人不归 2020-12-16 07:00

I would like to send a SOAP Message to a Web Service and read the response. My code is as follows: I will appreciate your help.

I hope my question is not repeate

相关标签:
4条回答
  • 2020-12-16 07:36

    The web service you are trying to consume offers a WSDL at the following address. So simply right click on the References in the solution explorer and use the Add Service Reference dialog in Visual Studio and point to the WSDL and it will generate strongly typed classes for you to easily consume the service, just like this:

    protected void sendSoapMessage()
    {
        using (var client = new RegistrationBindingsClient("RegistrationBindings"))
        {
            var registration = new RegistrationType();
            registration.Source = new SourceType();
            registration.Source.SourceID = "50001255";
            registration.Email = "adsvine@gmail.com";
            registration.FirstName = "Muz";
            registration.LastName = "Khan";
            var countryUK = new CountryTypeUK();
            countryUK.CountryID = 2000077;
            countryUK.Language = 2000240;
            countryUK.Address = new AddressTypeUK();
            countryUK.Address.Postalcode = "N19 3NU";
            registration.Item = countryUK;
            registration.DOB = new DateTime(1977, 3, 8);
            registration.Gender = 2000247;
    
            client.SubmitPanelist(registration);
        }
    }
    

    See how easy it is. You should not worry about any SOAP and XML plumbing.

    And if you are interested in the actual underlying SOAP envelope that is being sent on the wire using this request:

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <SubmitPanelist xmlns="http://www.greenfield.com/RegistrationGateway/Messages">
                <Registration xmlns="http://www.greenfield.com/RegistrationGateway/Types">
                    <Source>
                        <SourceID>50001255</SourceID>
                    </Source>
                    <Email>adsvine@gmail.com</Email>
                    <FirstName>Muz</FirstName>
                    <LastName>Khan</LastName>
                    <CountryUK>
                        <CountryID>2000077</CountryID>
                        <Language>2000240</Language>
                        <Income>0</Income>
                        <Education>0</Education>
                        <Address>
                            <Postalcode>N19 3NU</Postalcode>
                        </Address>
                    </CountryUK>
                    <DOB>1977-03-08</DOB>
                    <Gender>2000247</Gender>
                </Registration>
            </SubmitPanelist>
        </s:Body>
    </s:Envelope>
    
    0 讨论(0)
  • 2020-12-16 07:44

    Here's a general purpose class you can use to achieve what you need.

    IMPORTANT DISCLAIMER: You should only use this when you want (or need) to manually issue a SOAP-based web service: in most common scenarios you should definitely use the Web Service WSDL together with the Add Service Reference Visual Studio feature, which is the proper way to do that.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Xml;
    
    namespace Ryadel.Web.SOAP
    {
        /// <summary>
        /// Helper class to send custom SOAP requests.
        /// </summary>
        public static class SOAPHelper
        {
            /// <summary>
            /// Sends a custom sync SOAP request to given URL and receive a request
            /// </summary>
            /// <param name="url">The WebService endpoint URL</param>
            /// <param name="action">The WebService action name</param>
            /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
            /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
            /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
            /// <returns>A string containing the raw Web Service response</returns>
            public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
            {
                // Create the SOAP envelope
                XmlDocument soapEnvelopeXml = new XmlDocument();
                var xmlStr = (useSOAP12)
                    ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                        <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                          xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                          xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                          <soap12:Body>
                            <{0} xmlns=""{1}"">{2}</{0}>
                          </soap12:Body>
                        </soap12:Envelope>"
                    : @"<?xml version=""1.0"" encoding=""utf-8""?>
                        <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                            xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                            xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                            <soap:Body>
                               <{0} xmlns=""{1}"">{2}</{0}>
                            </soap:Body>
                        </soap:Envelope>";
                string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
                var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
                soapEnvelopeXml.LoadXml(s);
    
                // Create the web request
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Headers.Add("SOAPAction", soapAction ?? url);
                webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
                webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
                webRequest.Method = "POST";
    
                // Insert SOAP envelope
                using (Stream stream = webRequest.GetRequestStream())
                {
                    soapEnvelopeXml.Save(stream);
                }
    
                // Send request and retrieve result
                string result;
                using (WebResponse response = webRequest.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                    {
                        result = rd.ReadToEnd();
                    }
                }
                return result;
            }
        }
    }
    

    For additional info & details regarding this class you can also read this post on my blog.

    0 讨论(0)
  • 2020-12-16 07:48

    Is there any error message or did you use an HTTP monitor?

    Some maybe useful Links:

    • XmlDocument Save Method
    • How to: Send Data Using the WebRequest Class
    • Similar Question in stackoverflow maybe helpful
    0 讨论(0)
  • 2020-12-16 07:53

    You can access the service in 2 methods:

    1. By adding a web reference of the service. In visual studio you can right click on your project and select the option Add Web reference and then paste the URL of the service.

    2. Generate client proxy from the wsdl using wsdl tool from Visual studio command prompt.The command would be as follows:

    c:>wsdl "http://coreg.surveycenter.com/RegistrationGateway/PanelistService.asmx?wsdl

    It would generate a .cs file and an output.config. Include the .cs file in your project and you can directly use it to access the service. Make sure that the config file entries are added to your projects config.

    If you want to use HttpWebRequest then find the code below :

    string soap = 
    @"<?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:Body>
        <Register xmlns=""http://tempuri.org/"">
          <id>123</id>
          <data1>string</data1>
        </Register>
      </soap:Body>
    </soap:Envelope>";
    
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");
    req.Headers.Add("SOAPAction", "\"http://tempuri.org/Register\"");
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";
    
    using (Stream stm = req.GetRequestStream())
    {
         using (StreamWriter stmw = new StreamWriter(stm))
         {
              stmw.Write(soap);
         }
    }
    
    WebResponse response = req.GetResponse();
    
    Stream responseStream = response.GetResponseStream();
    // TODO: Do whatever you need with the response
    

    My Service looks like :

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomerWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string Register(long id, string data1)
        {
            return "ID.CUSTOMER";
        }
    }
    
    0 讨论(0)
提交回复
热议问题