In this short article I will explain how to call (consume) Web Service (ASMX) in Console application using C# and VB.Net.
Note: For illustration purpose, I am making use of the Free Web Service used for finding the geographical location of an IP Address.
Adding Reference of the Web Service in Visual Studio
1. Right click the project in Solution Explorer and choose Add Service Reference option from the context menu.
2. Now in the Add Service Reference Dialog you need to click on the Advanced button.
3. In the Service Reference Settings Dialog you need to click on Add Web Reference button.
4. Now in the Add Web Reference Dialog you need to add the URL of the Web Service and click the Green Go button to discover it. Once the Web Service is discovered, give its reference an appropriate name using the Web Reference Name TextBox and click on Add Reference button.
5. Finally you will notice the Web Service Reference has been added to your project.
Accessing the Web Service and its Methods in Console application
Using the Web Reference Name given in step #4, you can access the Web Service and its methods.
Fetching the location from the Web Service
Inside the Main method, first the IP Address is captured from the user input.
Then an object of GeoIPService is created and then the captured IP Address is passed as parameter to the GetGeoIP method which returns the name of the Country to which the IP address belongs.
Finally the country name is printed in the Console window.
static void Main(string args)
Console.Write("Enter IP Address: ");
string ipAddress = Console.ReadLine();
GeoService.GeoIPService service = new GeoService.GeoIPService();
GeoService.GeoIP output = service.GetGeoIP(ipAddress.Trim());
Console.WriteLine("Country: " + output.CountryName);
Console.Write("Enter IP Address: ")
Dim ipAddress As String = Console.ReadLine()
Dim service As New GeoService.GeoIPService()
Dim output As GeoService.GeoIP = service.GetGeoIP(ipAddress.Trim())
Console.WriteLine("Country: " + output.CountryName)