In this short article I will explain how to add reference of a Web Service (ASMX) in your project in Visual Studio 2010 / 2012 / 2013 and use it.
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
Using the Web Reference Name given in step #4, you can access the Web Service and its methods.
The HTML Markup consists of a TextBox, a Button and a Label control.
<asp:TextBox ID="txtIPAddress" runat="server" Text="" />
<asp:Button Text="Submit" runat="server" OnClick="GetCountry" />
<asp:Label ID="lblCountry" runat="server" />
Fetching the location from the Web Service
Inside the Button click event handler, an object of GeoIPService is created and then IP Address is passed as parameter to the GetGeoIP method which returns the name of the Country to which the IP address belongs.It is then displayed using the Label control.
protected void GetCountry(object sender, EventArgs e)
GeoService.GeoIPService service = new GeoService.GeoIPService();
GeoService.GeoIP output = service.GetGeoIP(txtIPAddress.Text.Trim());
lblCountry.Text = "Country: " + output.CountryName;
Protected Sub GetCountry(sender As Object, e As EventArgs)
Dim service As New GeoService.GeoIPService()
Dim output As GeoService.GeoIP = service.GetGeoIP(txtIPAddress.Text.Trim())
lblCountry.Text = "Country: " + output.CountryName