Webservices are used to share data between applications. Webservices are not .Net specific, but in .Net they are very easy to create. Webservices use XML to transfer data. In this example I will explain a webservice which returns the country based on an IP Address. It uses the code described in the article: Visitor's Country.
You can see the webservice in action by opening the following link: GetCountryFromIP.asmx
[Creating the Webservice]
If you create a new webservice using Visual Studio you will have your first working webservice. The code added by Visual Studio is basically all you need. It even contains a webmethod for the famous "Hello World". You can see the Hello World webservice by opening the following link: HelloWorld.asmx
1: using System;
2: using System.Collections;
3: using System.ComponentModel;
4: using System.Data;
5: using System.Diagnostics;
6: using System.Web;
7: using System.Web.Services;
8:
9: namespace markberck.WebServices
![]()
[GetCountry Method]
The webservice that is build uses the following code, you might recognize it from the article Visitor's Country. If added some extra input checks, because we cannot use RegularExpressionValidator on the input.
1: public string GetCountry(string IPAddress)
![]()
The current method isn't a webmethod yet. To do this you'll need to add the WebMethod attribute ([WebMethod]).
[GetCountry Method #2]
I've created an overload for the GetCountry Method, which doesn't need an IP Address as input. It uses the visitors IP Address (using HttpContext.Request.ServerVariables["REMOTE_ADDR"]) as input.
1: public string GetCountry()
![]()
Both methods aren't available as WebMethod, because they miss the [WebMethod] attribute. But if we add the attribute to both methods, you will receive an error when you open the webservice (it will compile without any warnings/errors). This is because there are two GetCountry methods. In a normal application they are distinguished by its signature (which variables (or of which type) it need as input, or which return type it has), but a WebService can't.
Therefore we have to describe the separate methods. The WebMethod attribute uses some properties for this; you can add a description (which is just what it says it is) and a MessageName. The MessageName property allows the method to be accessed by a different name. For the overload method (which returns your own country I've added the following attribute (with properties):
[WebMethod(
Description="Get Your Country",
MessageName="GetOwnCountry")]
For the original method, I've added the webmethod with different properties (with only a description):
[WebMethod(Description="Get Country for IP Address")]
[Adding it all together]
When we add this all into one class we'll end up with the following code:
1: using System;
2: using System.Web;
3: using System.Web.Services;
4: using System.Configuration;
5: using System.Data.SqlClient;
6:
7: namespace markberck.WebServices
![]()