How to call and authenticate (pass user credentials) to a Web Service using console application at run-time (programmatically)

Basically while calling a web service, we add service reference to the project. Visual studio automatically generates proxy for you and using that proxy class web service method will be called. But sometimes it is required to call a web service and authenticate it programmatically. There are ways to do this at run-time.

Below code explains the steps how to generate proxy, pass user credentials and call a web service programmatically at run-time.

  1. using System;  
  2. using System.Net;  
  3. using System.IO;  
  4.   
  5.   
  6. class ConnectToWebService  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             string sWebServiceUrl = "https://webservicename.com";  
  11.   
  12.             // Create a Web service Request for the URL.           
  13.             WebRequest objWebRequest = WebRequest.Create(sWebServiceUrl);  
  14.   
  15.             //Create a proxy for the service request  
  16.             objWebRequest.Proxy = new WebProxy();  
  17.   
  18.             // set the credentials to authenticate request, if required by the server  
  19.             objWebRequest.Credentials = new NetworkCredential("username""password");  
  20.             objWebRequest.Proxy.Credentials = new NetworkCredential("username""password");  
  21.   
  22.             //Get the web service response.  
  23.             HttpWebResponse objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();  
  24.   
  25.             //get the contents return by the server in a stream and open the stream using a                                                                   -            StreamReader for easy access.  
  26.             StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());  
  27.   
  28.             // Read the contents.  
  29.             string sResponse = objStreamReader.ReadToEnd();  
  30.             Console.WriteLine(sResponse);  
  31.             Console.ReadLine();  
  32.   
  33.             // Cleanup the streams and the response.  
  34.             objStreamReader.Close();  
  35.             objWebResponse.Close();  
  36.         }  
  37.     }