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.
- using System;
- using System.Net;
- using System.IO;
- class ConnectToWebService
- {
- static void Main(string[] args)
- {
- string sWebServiceUrl = "https://webservicename.com";
- // Create a Web service Request for the URL.
- WebRequest objWebRequest = WebRequest.Create(sWebServiceUrl);
- //Create a proxy for the service request
- objWebRequest.Proxy = new WebProxy();
- // set the credentials to authenticate request, if required by the server
- objWebRequest.Credentials = new NetworkCredential("username", "password");
- objWebRequest.Proxy.Credentials = new NetworkCredential("username", "password");
- //Get the web service response.
- HttpWebResponse objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
- //get the contents return by the server in a stream and open the stream using a - StreamReader for easy access.
- StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
- // Read the contents.
- string sResponse = objStreamReader.ReadToEnd();
- Console.WriteLine(sResponse);
- Console.ReadLine();
- // Cleanup the streams and the response.
- objStreamReader.Close();
- objWebResponse.Close();
- }
- }

ramakrishna barkamPosted Nov 8, 2018, 1:42 AM
Hi, How can I read username and password from the request?
harshad patelPosted Aug 10, 2018, 2:57 AM
How to add Authentication in soap service?
Shakir AliPosted Apr 8, 2018, 9:27 AM
@Rutika Banode Thank you so much for sharing this valuable information. You solved my problem.