Consume a SOAP webservice without adding a service reference

I needed these days to consume a very simple SOAP web service, but needed to do it directly from code in C#, without using the proxy classes / adding a service reference. Of course, it would have 0been easier, straightforward, etc, but for those who need to adopt (like myself due to certain constraints) this type of implementation, here it is just your basic example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;

namespace AIntegration
{
    public class OutgoingSOAP
    {
        public static string ATask(string uri, string soapOperation, string xmlRequestText)
        {
            string xmlResponseText = "";

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpRequest.Headers.Add("SOAPAction", soapOperation);
            httpRequest.ContentType = "text/xml;charset=utf-8";
            httpRequest.Method = "POST";

            XmlDocument xmlRequestDocument = new XmlDocument();
            xmlRequestDocument.LoadXml(xmlRequestText);

            using (Stream stream = httpRequest.GetRequestStream())
            {
                xmlRequestDocument.Save(stream);
            }

            using (WebResponse response = httpRequest.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    xmlResponseText = reader.ReadToEnd();
                }
            }

            return xmlResponseText;
        }
    }
}


Right, so right now you have this in your VS solution. What do you do with it? For me, this code actually went into a class, I then built my .dll (this was a class library project), and include it in my AX references. Again, this is for an AX 2009, since in AX 2012 you can use this directly in your AX instance, by doing a Visual Studio C# project. Then call this method from your code. Easy.

One more thing to mention here (quite important and nice to know) is the SOAP message envelope for which you can read more about at http://schemas.xmlsoap.org/soap/envelope/. And by extension the general SOAP details http://schemas.xmlsoap.org/soap/http/.

Finally, to summarize the SOAP XML message that you would be passing to the service in an example:

<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
 

1 comment:

  1. I got 500 Internal server when i tired tje code. Please help

    ReplyDelete