Calling a web service with C# and Visual Studio isn't that difficult as it maybe seems in the first place. In this post I will show how to add a service reference and use it when there is a Web Service Description Language aka WSDL available.

With the WSDL file Visual Studio automatically generates all necessary method calls for the WebService. You can later change the web service endpoint in the configuration file (e.g. web.config) if you have different development and production endpoints.

1. Add Web Service Reference in Visual Studio

Adding Service Reference in Visual Studio
Adding Service Reference in Visual Studio
Add Service and set Namespace
Add Service and set Namespace

2. Accessing the Web Service with C#

After Adding the web service reference in Visual Studio you can access the web service through the generate client which is named by the web service and client at the end.

In this example the Web Service returns the given city name and random values for the today's and tomorrow's weather.

static void Main(string[] args)
    {
      Console.WriteLine("Enter the city name and press Enter.");
      var cityname = Console.ReadLine();

      var weatherserviceclient = new LocalWeatherServiceClient();
      var weather = weatherserviceclient.GetWeatherForecastbyCity(cityname);

      var output = String.Format("The weather in {0} for today is {1} and tommorrow {2}", cityname, weather.Today, weather.Tommorrow);

      Console.WriteLine(output);
      Console.ReadLine();
    }

3. Result

Output of the program
Output of the program

If you are wondering where this web service is available - I just created one on my local machine for this tutorial :-). Probably I will create a tutorial for this too - so stay tuned.

You can also watch a very good YouTube Tutorial on this topic here: