Calling Web Service Using SOAP Request In Console Application

Background

There are many services available today such as WCF, REST, Web API etc., but still Web Service plays an important role in cross platform application communication such using  SAP web service to provide data for other platform applications.

Previously, I had written many articles on web services, from creating to consuming web services, and it got a huge response. Now in this article we will learn how to consume or call web services using SOAP request with the help of HttpWebRequest class. In this approach sometimes we need to consume the third party web services where we don't know much about the endpoints and configuration of web services. In this article we will not create any web service because we have already created it. So, if we want to learn the basics of the web services please refer to my previous articles.

I hope you read the above articles. Now let's learn how to call Web Service using SOAP request in console application step by step, so that beginners can also understand it easily.

Step 1: Find the Web Service SOAP Request Body.

In this article, we are not going to create web service because we have already created it and if you want to create web service and learn about it then please refer my preceding articles.

So let's find out the SOAP request body which is used to pass input parameters and invoke the web service. I have one web service which is hosted in my local IIS. So paste your web service url into the browser and wait till the following response comes which is shown in the following image.

In the above screenshot, you might have noticed that there are three web methods in the web service named Addition, EmployeeDetails and HelloWorld. Now click on one of the methods which you want to invoke. After clicking on web method it shows SOAP request and SOAP Response body, find out the SOAP request body which is shown in the following image.

In the above image, we are clearly observing that it shows all details how to make SOAP request and is also showing parameter values which are required to invoke service using HttpWebRequest. So, lets learn in brief about those parameters .

  •  HTTP Method: It's nothing but the what type of HTTP request you wants to make to the service such as GET , POST ,PUT or delete.
  •  Host: It defines the url where the service is hosted , in our scenario our host is localhost , i.e http://localhost/Employee.asmx.
  • Content-Type: It defines what type of content type request you are making such as XML or json now in our scenario its text/xml.
  • Content-Length: It defines the content length of request body.
  • SOAPAction: This is very important attribute to identify specific web method and call it from multiple web methods .
  • SOAP Body: It contains the request and response body.

I hope you learned about SOAP request parameter, Now copy the soap envelope part to use it as SOAP request which we will use in our console application.

Step 2: Create the Console application to call Web Service

  1. Go to "Start", "All Programs", then click "Microsoft Visual Studio 2015".
  2. Click "File", "New", then "Project...", and in the New Project window, click console "C#" - ".
  3. Give the project a name, such as "UsingSOAPRequest" or another as you wish and specify the location.

Now open Program.cs file and write the following method to create HttpWebRequest as:

public HttpWebRequest CreateSOAPWebRequest()    
{    
    //Making Web Request    
    HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");    
    //SOAPAction    
    Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");    
    //Content_type    
    Req.ContentType = "text/xml;charset=\"utf-8\"";    
    Req.Accept = "text/xml";    
    //HTTP method    
    Req.Method = "POST";    
    //return HttpWebRequest    
    return Req;    
}

Now let's create the method to invoke the web service using SOAP request body

public void InvokeService(int a, int b) {  
  //Calling CreateSOAPWebRequest method    
  HttpWebRequest request = CreateSOAPWebRequest();  
  
  XmlDocument SOAPReqBody = new XmlDocument();  
  //SOAP Body Request    
  SOAPReqBody.LoadXml(@ "<?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 >  
   < Addition xmlns = ""  
   http: //tempuri.org/"">    
   < a > " + a + @" < /a>   < b > " + b + @" < /b>   < /Addition>   < /soap:Body>   < /soap:Envelope>");    
  
  
   using(Stream stream = request.GetRequestStream()) {  
    SOAPReqBody.Save(stream);  
   }  
   //Geting response from request    
   using(WebResponse Serviceres = request.GetResponse()) {  
       using(StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) {  
           //reading stream    
           var ServiceResult = rd.ReadToEnd();  
           //writting stream result on console    
           Console.WriteLine(ServiceResult);  
           Console.ReadLine();  
       }  
   }  
} 

Now call the above method from main method by writing the following code as:

static void Main(string[] args)    
{    
    //creating object of program class to access methods    
    Program obj = new Program();    
    Console.WriteLine("Please Enter Input values..");    
    //Reading input values from console    
    int a = Convert.ToInt32(Console.ReadLine());    
    int b = Convert.ToInt32(Console.ReadLine());    
    //Calling InvokeService method    
    obj.InvokeService(a, b);    
}

Now whole code in Program.cs file will look like the following:

using System;  
using System.IO;  
using System.Net;  
using System.Xml;  
  
namespace UsingSOAPRequest  
{  
    public class Program  
    {  
        static void Main(string[] args)  
        {  
            //creating object of program class to access methods  
            Program obj = new Program();  
            Console.WriteLine("Please Enter Input values..");  
            //Reading input values from console  
            int a = Convert.ToInt32(Console.ReadLine());  
            int b = Convert.ToInt32(Console.ReadLine());  
            //Calling InvokeService method  
            obj.InvokeService(a, b);  
        }  
        public void InvokeService(int a, int b)  
        {  
            //Calling CreateSOAPWebRequest method  
            HttpWebRequest request = CreateSOAPWebRequest();  
  
            XmlDocument SOAPReqBody = new XmlDocument();  
            //SOAP Body Request  
            SOAPReqBody.LoadXml(@"<?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>  
                <Addition xmlns=""http://tempuri.org/"">  
                  <a>" + a + @"</a>  
                  <b>" + b + @"</b>  
                </Addition>  
              </soap:Body>  
            </soap:Envelope>");  
  
  
            using (Stream stream = request.GetRequestStream())  
            {  
                SOAPReqBody.Save(stream);  
            }  
            //Geting response from request  
            using (WebResponse Serviceres = request.GetResponse())  
            {  
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))  
                {  
                    //reading stream  
                    var ServiceResult = rd.ReadToEnd();  
                    //writting stream result on console  
                    Console.WriteLine(ServiceResult);  
                    Console.ReadLine();  
                }  
            }  
        }  
  
        public HttpWebRequest CreateSOAPWebRequest()  
        {  
            //Making Web Request  
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");  
            //SOAPAction  
            Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");  
            //Content_type  
            Req.ContentType = "text/xml;charset=\"utf-8\"";  
            Req.Accept = "text/xml";  
            //HTTP method  
            Req.Method = "POST";  
            //return HttpWebRequest  
            return Req;  
        }  
    }  
}

Now run the console application,  then the console window will look like as follows and enter the input values as:

Now press enter button, it will give the response in XML format as follows:

In preceding console window you have seen web service response in the form of XML format which contains the output as 300. I hope from all above examples you have learned how to call web service using SOAP request in console application.

Notes

  • Download the Zip file of the sample application for a better understanding.
  • Apply proper validation as per your need.

Summary

I hope this article is useful for all readers, if you have any suggestions related to this article then please contact me.

Read more articles on ASP.NET Web Services


Similar Articles