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:
  1. public HttpWebRequest CreateSOAPWebRequest()    
  2. {    
  3.     //Making Web Request    
  4.     HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");    
  5.     //SOAPAction    
  6.     Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");    
  7.     //Content_type    
  8.     Req.ContentType = "text/xml;charset=\"utf-8\"";    
  9.     Req.Accept = "text/xml";    
  10.     //HTTP method    
  11.     Req.Method = "POST";    
  12.     //return HttpWebRequest    
  13.     return Req;    
  14. }    
Now let's create the method to invoke the web service using SOAP request body
  1. public void InvokeService(int a, int b) {  
  2.   //Calling CreateSOAPWebRequest method    
  3.   HttpWebRequest request = CreateSOAPWebRequest();  
  4.   
  5.   XmlDocument SOAPReqBody = new XmlDocument();  
  6.   //SOAP Body Request    
  7.   SOAPReqBody.LoadXml(@ "<?xml version="  
  8.    "1.0"  
  9.    " encoding="  
  10.    "utf-8"  
  11.    "?>   < soap: Envelope xmlns: soap = ""  
  12.    http: //schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">    
  13.    < soap: Body >  
  14.    < Addition xmlns = ""  
  15.    http: //tempuri.org/"">    
  16.    < a > " + a + @" < /a>   < b > " + b + @" < /b>   < /Addition>   < /soap:Body>   < /soap:Envelope>");    
  17.   
  18.   
  19.    using(Stream stream = request.GetRequestStream()) {  
  20.     SOAPReqBody.Save(stream);  
  21.    }  
  22.    //Geting response from request    
  23.    using(WebResponse Serviceres = request.GetResponse()) {  
  24.        using(StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) {  
  25.            //reading stream    
  26.            var ServiceResult = rd.ReadToEnd();  
  27.            //writting stream result on console    
  28.            Console.WriteLine(ServiceResult);  
  29.            Console.ReadLine();  
  30.        }  
  31.    }  
  32. }  
Now callthe above method from main method by writing the following code as:
  1. static void Main(string[] args)    
  2. {    
  3.     //creating object of program class to access methods    
  4.     Program obj = new Program();    
  5.     Console.WriteLine("Please Enter Input values..");    
  6.     //Reading input values from console    
  7.     int a = Convert.ToInt32(Console.ReadLine());    
  8.     int b = Convert.ToInt32(Console.ReadLine());    
  9.     //Calling InvokeService method    
  10.     obj.InvokeService(a, b);    
  11. }    
Now whole code in Program.cs file will look like the following:
  1. using System;  
  2. using System.IO;  
  3. using System.Net;  
  4. using System.Xml;  
  5.   
  6. namespace UsingSOAPRequest  
  7. {  
  8.     public class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             //creating object of program class to access methods  
  13.             Program obj = new Program();  
  14.             Console.WriteLine("Please Enter Input values..");  
  15.             //Reading input values from console  
  16.             int a = Convert.ToInt32(Console.ReadLine());  
  17.             int b = Convert.ToInt32(Console.ReadLine());  
  18.             //Calling InvokeService method  
  19.             obj.InvokeService(a, b);  
  20.         }  
  21.         public void InvokeService(int a, int b)  
  22.         {  
  23.             //Calling CreateSOAPWebRequest method  
  24.             HttpWebRequest request = CreateSOAPWebRequest();  
  25.   
  26.             XmlDocument SOAPReqBody = new XmlDocument();  
  27.             //SOAP Body Request  
  28.             SOAPReqBody.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>  
  29.             <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"">  
  30.              <soap:Body>  
  31.                 <Addition xmlns=""http://tempuri.org/"">  
  32.                   <a>" + a + @"</a>  
  33.                   <b>" + b + @"</b>  
  34.                 </Addition>  
  35.               </soap:Body>  
  36.             </soap:Envelope>");  
  37.   
  38.   
  39.             using (Stream stream = request.GetRequestStream())  
  40.             {  
  41.                 SOAPReqBody.Save(stream);  
  42.             }  
  43.             //Geting response from request  
  44.             using (WebResponse Serviceres = request.GetResponse())  
  45.             {  
  46.                 using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))  
  47.                 {  
  48.                     //reading stream  
  49.                     var ServiceResult = rd.ReadToEnd();  
  50.                     //writting stream result on console  
  51.                     Console.WriteLine(ServiceResult);  
  52.                     Console.ReadLine();  
  53.                 }  
  54.             }  
  55.         }  
  56.   
  57.         public HttpWebRequest CreateSOAPWebRequest()  
  58.         {  
  59.             //Making Web Request  
  60.             HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");  
  61.             //SOAPAction  
  62.             Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");  
  63.             //Content_type  
  64.             Req.ContentType = "text/xml;charset=\"utf-8\"";  
  65.             Req.Accept = "text/xml";  
  66.             //HTTP method  
  67.             Req.Method = "POST";  
  68.             //return HttpWebRequest  
  69.             return Req;  
  70.         }  
  71.     }  

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

Up Next
    Ebook Download
    View all
    Learn
    View all