How to Create a Web Service in ASP.Net

Web services are indivisible parts of web development as they provide mechanisms to share and communicate with data across different platforms and applications. It is a great way of exchanging data between two web applications. By using Web services, your application can publish its function or message to the rest of the world. For example a weather company can provide a web service where the clients can use it to get the weather information for different locations. Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).

What are Web Services?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

Creating a Web Service

Now let's start creating a very simple web service that will provide information about the client's IP address and browser. Creating a web service with Visual Studio is a very simple task since most of it is handled by Visual Studio.

First thing we need to do is to create an ASP.Net web site or open an existing one within Visual Studio. Next we add web service file (UserInfoService.asmx) through Add New Item dialog box. Note that you can name it whatever you want but for our purpose I will name it UserInfoService.asmx. It will add tow files with .asmx and .vb (if you use VB.Net) extensions. The .asmx file is the actual web service file and .vb is the code behind file. Of course you could put the code behind file content into .asmx file but it is advised to keep them separate since you won't get intellisense in .asmx file while coding or editing. By default when we add a web service to our projects the VS generates some code for us in .vb file with Hello World method like this:

Code Example (VB.Net)

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

'To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
'<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class UserInfoService
     Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
        Uri()
    End Function

End Class

As you can see the .vb file contains a simple class that is decorated with some attributes. One of the most important attribute is the WebMethod which makes the method as a web service method. In general you should change the namespace from http://tempuri.org/ to the website name the web service resides (should be unique). It should be an URL but doesn't have to be a working one. For this project I will change the namespace to http://code2point.com/ and the Hello World method with the ones shown below:

Code Example (VB.Net)

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

'To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
'<System.Web.Script.Services.ScriptService()> _
<WebService(Description:="This is a very simple web service that provides information about the client.", _
            Name:="User-Info Web Service", Namespace:="http://code2point.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class UserInfoService
    Inherits System.Web.Services.WebService

    <WebMethod(Description:="Gets the user's IP address.")> _
    Public Function GetUserIp() As String
        Return My.Request.UserHostAddress
    End Function

    <WebMethod(Description:="Gets the user agent (browser) information.")> _
    Public Function GetUserAgent() As String
        Return My.Request.UserAgent
    End Function

    <WebMethod(Description:="Gets a Boolean value that specifies whether JavaScript is supported on the client's browser.")> _
    Public Function JavaScriptSuport() As Boolean
        Return My.Request.Browser.EcmaScriptVersion.Major >= 1
    End Function

End Class

We have replaced the Hello Word method with GetUserIp, GetUserAgent and JavaScriptSuport methods which use My.Request objects' methods to return simple type values.
We can as well return more complex types. For example we could return objects such as structures, arrays or an array of some reference type. Just to give you a glance of what it would look like on the browser, if we use an array of Book type that has Author, Title and Count as its members, I present you with the screen shot on the right. In order for this to work one of the returning type's constructors should be the default constructor, otherwise XmlSerializer will fail. Note this requirement is only for complex data types. One reason to use web services is that we can share objects very easily between web applications. As you can guess we don't need to parse any object while we use web services. This is done automatically by the platform it resides. Because of this web services become more popular today. In my next post How to Use a Web Service in ASP.Net I will show you how to use a web service and how it works.

Also note that I added description attributes to the methods above. These will allow us to show the methods' descriptions on the browser when we navigate to the web service endpoint.



blog comments powered by Disqus