Click here to Skip to main content
14,356,314 members

Web Services:From a beginner's perspective

Rate this:
4.50 (31 votes)
Please Sign up or sign in to vote.
4.50 (31 votes)
1 Mar 2013CPOL
This article tries to dig in as to what are WebServices,how to create them and how to call and use them in various scenarios.


WebServices : As the name implies, A WebService is an entity or a piece of code which is hosted on the Web, which serves a specefic purpose. This could be the most simple framed definition.

A more apt version may be: A WebService is a part fo a software application which is hosted on the Web and which does a particular function in order to execute the business logic.

Further, a WebService allows a website to interact with other websites irrespective of the programming language the websites's been written in and also irrespective of the hardware & OS concerns of the machines.

Lets take an example over here: Suppose, you are a developer and you have some 3 different mathematical websites under you, demanded by various clients.A common functionality needs to be implemented in all the 3 websites, lets say displaying a Fibonaaci series in a text area.

The question which arises here is, are you gonna write separate piece of codes to have the same functionality 3 times.Well it would be a redundant extra effort, if you would try to aim at this approach.Here, the need for a WebService comes into picture. Code the functionality of displaying a Fibonaaci series in a WebService just once, and call this webservice in the 3 different websites.There you go, you are done.You need not write the same code thrice or else.

One question that may arise over here is: Why WebServices now?What was the case earlier?Were people able to leverage the functionalities of one application to another application?

The answer is yes, people were able to do so.There were technologies such as COM (Component Object Model), DCOM (Distributed Component Object Model) which were helpful in achieving this leverage, but they had their limitations as well. Infact they had to be explicitly registered on each user's machine, thus giving chances for registery glitches and stuffs.

A WebService overcomes all those limitations.

The aim of this artcle is to make a person understand what's a webservice (which I have tried to do in the Introduction section) and "How to create a WebService and call & use them via different methods?".The later will be discussed in the below coming sections. Stay tuned..


Well I belong to the .NET domain and the code files in this article aim at .NET 3.5, so the only pre-requisite would be the presence of Visual Studio 2008 client.

Using the code

Lets start with the creation of the WebService.

1) Open Visual Studio 2008 Client.Click on New>WebSite>ASP.NET Web Service.Give the path where you want to place the code. Refer to the below screenshots.

Image 1

Image 2

2) Visual Studio will open a default Service.cs file in which you can write your methods.Write the below lines of code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
[WebService(Namespace= "")]
[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 public class Service : System.Web.Services.WebService
public Service ()
//Uncomment the following line if using designed components 
	public int Area(int l, int b)
	return l * b;
	public int Perimeter(int l, int b)
	return 2 * (l +b);

3) Build the solution and view the Service.asmx file in the browser. It will be something like below: 

Image 3 

4) The Web Methods created will be evident and will be invoked via HTTP POST method if the links Area and Perimeter are clicked.

Image 4 

So here it is, a very basic WebService has been coded and created, which will help us to calculate the area and perimeter of a rectangle.

You might wana copy the Web Service URL because they are used later in the article. 

Next, we will see how to call and use the Web Service in times of need.

Well, there may be 3 methods by which a Web Service is called, depending upon the scenarios. 

1)       By HTTP POST method.<o:p>

2)       By creating a Proxy Class 

3)       By using XMLHTTP Request object over SOAP 

Let's discuss each of them in brief:    

HTTP POST method: This method can be used directly by calling the .asmx file from the client.

The most favorable method to execute an HTTP POST method is to have the codes inside an HTML file. Let’s get started to implement it.

Open your notepad and write the below lines of code in it:


<title>WebService Call using HTTP POST</title>
	<form action="http://localhost:43529/WebService/Service.asmx/Area" method="POST">
	<input name="l">
	<input name="b">
	<input type="submit" value="Click for Area">
	<form action="http://localhost:43529/WebService/Service.asmx/Perimeter" method="POST">
	<input name="l">
	<input name="b">
	<input type="submit" value="Click for Perimeter">

Just a friendly reminder, you would wana change the Web Service URL in the above code, by your own URL, which you would have copied sometime earlier..Smile | :)  

The bold lines of code exhibit as to how we can call the methods of the WebService separately via HTTP POST. Upon saving the above lines of code as .html and executing it will result in a browser action. 

Image 6  


 Image 7

 When the button “Click for Area” or “Click for Perimeter” is clicked, we would see that the specific methods of the WebService are called and the result is in the form of an XML.


One of the limitations of HTTP POST method can be thought as of: We are unable to build Web Methods which take complex types as parameter or return values.

 2)      Creation of a Proxy Class: This method is widely used by developers. This method actually makes use of the full potential of a Web Service. Let’s implement this and see its wonders.

We need to create one ASP.NET website to see and implement this method.

Open Visual Studio once again and click on New>Website>ASP.NET Website. Give the path where you want to place the code. 

Image 8


This web site creation will open a Default.aspx page, its aspx.cs page, an App_Code folder and few more stuffs.

Open the Default.aspx page and design it as per below screenshot:

It’s basically 4 ASP label controls, 4 ASP text box controls and 1 ASP button bound under 1 div.

Image 9 

Now the most important aspect of this very method comes into play. Addition of the previously created Web Service.

Right-click the project and click on “Add Web Reference”. The click will open a dialog box similar to the below screenshot.

Image 10 

Now, we need to catch the Web Service here either by adding the URL or by browsing through the various options given. Successful addition of the Web Service will yield “Web services found at this URL”. You would see the methods that you have actually created. You might want to change the name of the web reference from “localhost” to something else to avoid confusion and stuffs. Click on Add Reference and there you go. You have successfully added a Web Reference to your ASP.NET website.

Image 11 

The solution explorer will be something like below:

Image 12 

Now, once the Web Reference is added, let’s write some code in Code-Behind to make use of the web service.

Open Default.aspx.cs file and on Button Click event, add the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partialclass_Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
 protected void btnClick_Click(object sender, EventArgs e)
	if (!string.IsNullOrEmpty(txtLength.Text) && !string.IsNullOrEmpty(txtBreadth.Text))
	Maths.Service obj = new Maths.Service();
	int l = Convert.ToInt32(txtLength.Text);
	int b = Convert.ToInt32(txtBreadth.Text);
  	txtArea.Text = Convert.ToString(obj.Area(l, b));
  	txtPerimeter.Text = Convert.ToString(obj.Perimeter(l, b));

Now, let me explain the above code further. The bold line of code is what this method is all about, Creation of proxy class.

We are making an object of the Web Service added and then are using that object to call the individual methods of the WebService. Rest of the code is self-explanatory, which will calculate the area and perimeter of the rectangle.

Build the solution and view the Default.aspx file in the browser.

Enter some values for length and breadth and click on the button.

You will see the area and perimeter displayed in the placed textboxes.

Similar screenshots are below. 

Image 13

Image 14

We see in this method that we can call a Web Service by just adding a Web Reference and creating a proxy class and without even coding the required functionality (done by the Web Service) in the current project.

1)    By using XMLHTTP Request object over SOAP:<o:p>

First let’s see what SOAP is.

SOAP (Simple Object Access Protocol) is a protocol used for messaging and is completely XML based.

SOAP provides a complete set of rules for messages and also, rules for entities like message encoding, message handling etc. 

Syntax of a SOAP message will be as follows:

<?xml version="1.0" encoding="utf-8"?><o:p>

<soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap=""><o:p>




A SOAP message is called an Envelope, which further has Header and Body tags.

Header tag is optional whereas Body tag is mandatory to use in order to submit a message.

Now, let’s see what exactly XMLHttpRequest is.

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script.

In this implementation we will use an HTML form and a JavaScript function to demonstrate the full potential of this method.

a) First of all we will create an object of XMLHttpRequest. Refer the below lines of code. 

var sample;
if (window.XMLHttpRequest) 
sample= new window.XMLHttpRequest;//For browsers other than IE
sample=new ActiveXObject("MSXML2.XMLHTTP.3.0"); //for IE   


b) Now, we will set the Web Service URL using the Open method of XMLHttpRequest. ("POST",”http://localhost:43529/WebService/Service.asmx",true);  

Basically Open method of XMLHttpRequest has 5 parameters:

 Type of HTTPMethod, Url, Boolean value (true most of the times), Username and password (optional).

c) Now, we will create the Request Headers and SOAP request (Shown in the below code).

d) The demonstration will be basically done by an HTML code. Hence open your notepad and type in the below code:  

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<script type="text/javascript" >

var sample;
if (window.XMLHttpRequest) 
	sample = new window.XMLHttpRequest;

	sample = new ActiveXObject("MSXML2.XMLHTTP.3.0");
catch (ex) 

}"POST", "http://localhost:43529/WebService/Service.asmx",true);
	sample.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	sample.setRequestHeader("SOAPAction", "");

	strRequest = "<?xml version='1.0' encoding='utf-8'?>";
	strRequest = strRequest + "<soap:Envelope " +"xmlns:xsi='' " +"xmlns:xsd='' " +"xmlns:soap=''>";
	strRequest = strRequest + " <soap:Body>";
	strRequest = strRequest + "<Area xmlns=''><l>4</l><b>5</b></Area>";
	strRequest = strRequest + "</soap:Body>";
	strRequest = strRequest + "</soap:Envelope>";

	sample.onreadystatechange = function () {
	if (sample.readyState == 4 &&xmlHTTP.status == 200) 



e) Save the notepad as .html extension and execute it to have a browser action. 

The browser will give the output as a JavaScript alert box, similar to below.

Image 15 

 SetRequestHeader creates the Header tag of the SOAP message, while OnReadyStateChange property of XMLHTTPRequest object assists us to execute the code after the response from the Web Service is processed. 

Points of Interest 

Initially i used to think web services,wcf's and stuffs are aliens, and had no interests in them at all.

Interests in Web Services grew when I got a .NET project dealing with web services, wcf services and else, had to learn them you know. Now I know that they are damn helpful..Smile | :)  

Well, wasn't really successful in finding a great resource for a beginner(including me) under this topic, hence decided to pen down something.

First article at CP...Smile | :) Comments and criticisms are pretty welcome. And please don't mind much on the formatting, had a hart time doing it....:P


28th Feb 2013 Version 1.0


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Anurag Sinha V
Systems Engineer
India India
An electronics engineer landed in the crazy .NET world...Smile | :) Smile | :)

Comments and Discussions

Questionis there is a complete example of the article Pin
samerselo17-Aug-15 10:22
membersamerselo17-Aug-15 10:22 
QuestionVery good article for beginners... Pin
Rohcode5-May-15 1:08
memberRohcode5-May-15 1:08 
QuestionGreat article for beginers on WebService Pin
Rohcode20-Feb-15 0:51
memberRohcode20-Feb-15 0:51 
AnswerRe: Great article for beginers on WebService Pin
Anurag Sinha V10-Mar-15 21:52
memberAnurag Sinha V10-Mar-15 21:52 
Questioncomment Pin
pankajpandey111024-Dec-14 0:29
memberpankajpandey111024-Dec-14 0:29 
QuestionHow response captured in alert message with out sending request ? Pin
venkata chaitanya29-Oct-14 21:25
membervenkata chaitanya29-Oct-14 21:25 
Questiongreat Pin
Member 1070043031-Jul-14 1:41
memberMember 1070043031-Jul-14 1:41 
Questionwebservice sample with json Pin
Mehdipirmoradian21-Mar-14 13:39
memberMehdipirmoradian21-Mar-14 13:39 
Questionvery nice article for beginers Pin
sunneil chy16-Nov-13 8:55
membersunneil chy16-Nov-13 8:55 
QuestionVery helpful Pin
Member 1005074219-Sep-13 20:59
memberMember 1005074219-Sep-13 20:59 
AnswerRe: Very helpful Pin
Anurag Sinha V19-Sep-13 21:41
memberAnurag Sinha V19-Sep-13 21:41 
GeneralRe: Very helpful Pin
Member 1005074220-Sep-13 0:28
memberMember 1005074220-Sep-13 0:28 
GeneralRe: Very helpful Pin
Anurag Sinha V20-Sep-13 2:25
memberAnurag Sinha V20-Sep-13 2:25 
QuestionHow to use for Windows phone 7,8 apps? Pin
SagarAnand01526-Aug-13 11:01
professionalSagarAnand01526-Aug-13 11:01 
AnswerRe: How to use for Windows phone 7,8 apps? Pin
Anurag Sinha V27-Aug-13 23:37
memberAnurag Sinha V27-Aug-13 23:37 
QuestionSecurity Error Pin
kryz_rock21-Aug-13 11:17
memberkryz_rock21-Aug-13 11:17 
AnswerRe: Security Error Pin
Anurag Sinha V21-Aug-13 19:47
memberAnurag Sinha V21-Aug-13 19:47 
GeneralRe: Security Error Pin
kryz_rock22-Aug-13 5:19
memberkryz_rock22-Aug-13 5:19 
QuestionThis was just what I was looking for. Pin
rleonard457724-May-13 9:27
memberrleonard457724-May-13 9:27 
GeneralThank you Pin
Vunnam2720-May-13 19:00
memberVunnam2720-May-13 19:00 
GeneralRe: Thank you Pin
Anurag Sinha V20-May-13 22:31
memberAnurag Sinha V20-May-13 22:31 
QuestionGood artical simply enough for beginner Pin
Member 58993612-Apr-13 23:59
memberMember 58993612-Apr-13 23:59 
AnswerRe: Good artical simply enough for beginner Pin
Anurag Sinha V3-Apr-13 0:38
memberAnurag Sinha V3-Apr-13 0:38 
QuestionASMX is NOT in use any more Pin
sukumarraju1-Mar-13 4:31
membersukumarraju1-Mar-13 4:31 
AnswerRe: ASMX is NOT in use any more Pin
Anurag Sinha V1-Mar-13 5:49
memberAnurag Sinha V1-Mar-13 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 28 Feb 2013


56 bookmarked