Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Understanding the Basics of Web Service in ASP.NET

0.00/5 (No votes)
10 Jun 2012 1  
Understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Introduction

This article aims at understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Background

Connectivity between applications is very important. Connectivity in any case is very important for that matter but it specially is very important between applications. Connecting web application used to be a big challenge before the advent of technologies like SOAP (Simple Object Access Protocol). The reason it was so difficult was, there were so many technologies people were working in. The applications were hosted on different types of servers, etc. But these things should not be a barrier to facilitate the communication between applications. The only requirement was to have some standards to follow and standard ways of doing things so that the applications become capable of communicating with other applications irrespective of the technologies used.

SOAP and Web Services

SOAP and XML created the solution for the problem that developers were facing before. SOAP is a standard XML based protocol that communicated over HTTP. We can think of SOAP as message format for sending messaged between applications using XML. It is independent of technology, platform and is extensible too.

We have SOAP and XML to give us connectivity between applications. Does it mean that I have to write XML and SOAP specific things myself to facilitate this communications? I could do that but that will be very time consuming and sometimes error prone too.

Where does Web Services come in picture? Well, Web services is the mechanism that ASP.NET framework provides to make it easy for us to write code to facilitate connectivity between applications. As ASP.NET developer, If I need an application that will be used by many other applications then I can simply decide to write a web service for it and ASP.NET framework will take care of doing the low level SOAP and XML work for us.

The other side of the coin is, if our ASP.NET application wants to use a web service, i.e., an application that is providing me SOAP based interface for communication. So what we are going to do now is write a small Web service to see how we can have our application communication-ready for other applications and secondly, we will try to consume a webservice to understand how we can use other applications from our application.

Web service article image

Creating a Web Service

Let us write a simple module that will provide basic arithmetic operations to other applications. The user of our application will have to provide us 2 numbers and we will perform the requested operation like Addition, Subtraction and Multiplication.

So, the first thing we need to do is to create our web service. We can do this by creating a website of type ASP.NET Web service. This will give us a skeleton to write our web service code in.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
}

The attribute WebService tells that this class contains the code for web service. The namespace is what is used to identify the web service. The WebMethod attribute specifies the methods which our web service is providing.

Let us now go ahead and write code to have our functions in this webservice.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service ()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public int Add(int x, int y)
    {
        return x+y;
    }

    [WebMethod]
    public int Subtract(int x, int y)
    {
        return x - y;
    }

    [WebMethod]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

We have a very basic web service implemented which can let the user have some basic arithmetic operations. Now to create the WebService binary, we will have to use the following command on Visual Studio Command Prompt.

>CSC /t:library /out:ArithmeticServiceImpl.dll App_code\Service.cs

This will create a DLL file for our web service. This DLL file can be used by any client by using the SOAP protocol. If we need to test our web service for how it works over the SOAP protocol, we can view the service.asmx file in the browser and see what functions our web service is exposing.

Web service article image

We can even test these methods here and see the XML file that contains the service description.

Consuming a WebService

There are three ways we can consume a WebService:

  1. Using HTTP-POST method.
  2. Using XMLHttp that will use SOAP to call our the service
  3. Using WSDL generated proxy class

The HTTP-Post method can be used by calling .asmx file directly from client. We can directly use the method name and the parameter names will be taken from our input fields on form.

<html>
    <body>
        <form action="http://localhost/.../Service.asmx/Multiply"  method="POST">
                <input name="x"></input>
                <input name="y"></input>

                <input type="submit" value="Enter"> </input>
        </form>
    </body>
</html>

When this form get submitted, the web service's method will be called. The second method where we can use the XMLHttp over SOAP to access the webservice is used when we want to use the web service using full capability of SOAP.

The third way of using the web service is by generating a Proxy class for the web service and then using that proxy class. This method is, to me, more type safe and less error prone as once we have the proxy class generated, it can take care of SOAP messages, serialization and ensure that all the problems can be handled at compile time instead of runtime.

To use this service, we need to do "Add Web reference" and add the webservice reference. Alternatively I can also use WSDL.exe, a command line tool, to generate the proxy classes and use them. "Add web Reference" is also using the same WSDL.exe to generate the proxy classes.

Web service article image

Now let us write some code to use the proxy class to perform the operations, the proxy class will then communicate to the web service using SOAP and get back the results to us.

protected void Button1_Click(object sender, EventArgs e)
{
    if (txtX.Text != string.Empty
        && txtY.Text != string.Empty)
    {
        try
        {
            int x = Convert.ToInt32(txtX.Text);
            int y = Convert.ToInt32(txtY.Text);

            ArithmeticService.Service service = new ArithmeticService.Service();

            Label1.Text = "Sum: " + service.Add(x, y).ToString();
            Label2.Text = "Difference: " + service.Subtract(x, y).ToString();
            Label3.Text = "Multiplication: " + service.Multiply(x, y).ToString();
        }
        catch(Exception)
        {
            throw;
        }
    }
}

Let us run the website to see the results

Web service article image

Points of Interest

We saw how to create a web service in ASP.NET and how we can consume a web service in ASP.NET. One interesting area that we did not see here is how we can use web service from AJAX. ASP.NET also provides a mechanism using scriptManager that will generate the JavaScript proxy for a webservice and we can use it to call the webservice methods. Also, if we want to customize the security of our web service, we can do that too using custom SOAP headers.

History

  • 27 Feb 2012: Understanding the basics of Web Service in ASP.NET

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here