Web service

An web service is basically like a SOAP server in that it “talks” from the client-server in XML with the client requesting the function on the server and obtaining a result.

I am using mono to compile and run the web service since I am running apache on Linux (kubuntu) (here is how I setup the mono apache module within k/ubuntu).

To start with, you need to create a web service instance and what language you are going to be using (since using mono then c#) and also the class that you want to “expose” to the web service itself.

<%@ WebService language="C#" class="FirstWebService" %>

after that you then need to add the attribute to the class to tell the compiler that the class is going to be a webservice and what the base directory is going to be (I created a new directory within the apache hosting directory), since we are writing a WebService we need to inherit from a System.Web.Services.WebService

[WebService(Namespace="http://localhost/csharp/")]
public class FirstWebService : WebService

and then just within the class structure you only need to tell the function with a attribute heading of [WebMethod] that it is going to be “exposed” to the web service, if you do not put that in, it will be “exposed” to the web service and thus the client cannot access that method.

    [WebMethod]
    public int Add(int a, int b)

and that is about it, the mono (and of course .net base framework) will create the rest of the WSDL and additional parts for a WebService.

Here is the full web service code in full, save this as web_service.asmx (the asmx means a web service extension)

<%@ WebService language="C#" class="FirstWebService" %>
 
using System;
using System.Web.Services;
 
// expose as the web service
[WebService(Namespace="http://localhost/csharp/")]
public class FirstWebService : WebService
{
    // expose as a web method
    [WebMethod]
    public int Add(int a, int b)
    {
        return TheAddingMethod(a,b);
    }
 
    // this one will not be exposed since it does not have the [WebMethod] attribute
    public int TheAddingMethod(int a, int b)
    {
	// but since it is part of the class you can still call class methods etc.
	return a+b;
    }
}

and when you goto the web URL for the webservice you should see something similar to this

The FirstWebService URL
The FirstWebService URL

if you click on the left menu “add” and then “test form” to test the webservice, it will bring up a window similar to the below, I have done a full test with adding 4 + 5 = 9

Testing the first web service
Testing the first web service

Leave a Reply

Your email address will not be published.