Click here to Skip to main content
15,881,139 members
Articles / Web Development / ASP.NET

Web Services:From a beginner's perspective

Rate me:
Please Sign up or sign in to vote.
4.50/5 (31 votes)
1 Mar 2013CPOL8 min read 113K   57   27
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.

Introduction:

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..



Background 

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. 

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
 
[WebService(Namespace= "http://tempuri.org/")]
[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
//
[System.Web.Script.Services.ScriptService]
 public class Service : System.Web.Services.WebService
{
public Service ()
{
 
//Uncomment the following line if using designed components 
//InitializeComponent();
}
 
    [WebMethod]
	public int Area(int l, int b)
    	{
	return l * b;
    	}
 
    [WebMethod]
	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:

<o:p>  

HTML
<html>
<head>
<title>WebService Call using HTTP POST</title>
	<body>
	<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>
	<form action="http://localhost:43529/WebService/Service.asmx/Perimeter" method="POST">
	<input name="l">
	<input name="b">
	<input type="submit" value="Click for Perimeter">
	</form>
	</body>
</head>
</html> 

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  

W  

 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:

C#
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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><o:p>

<soap:Body> 

</soap:Body><o:p>

</soap:Envelope>

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. 

JavaScript
var sample;
if (window.XMLHttpRequest) 
{
sample= new window.XMLHttpRequest;//For browsers other than IE
}
else 
{
try 
{
sample=new ActiveXObject("MSXML2.XMLHTTP.3.0"); //for IE   
}
catch(ex) 
{

}
}

b) Now, we will set the Web Service URL using the Open method of XMLHttpRequest.

sample.open ("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:  

JavaScript
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" >

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

else 
{
try 
{
	sample = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) 
{

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

	strRequest = "<?xml version='1.0' encoding='utf-8'?>";
	strRequest = strRequest + "<soap:Envelope " +"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
	strRequest = strRequest + " <soap:Body>";
	strRequest = strRequest + "<Area xmlns='http://tempuri.org/'><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) 
{
	alert(xmlHTTP.responseXML.xml);
}
}
sample.send(strRequest);

</script>
</head>
<body>

</body>
</html>  

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

History

28th Feb 2013 Version 1.0

License

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


Written By
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 9:22
samerselo17-Aug-15 9:22 
QuestionVery good article for beginners... Pin
Rohcode5-May-15 0:08
Rohcode5-May-15 0:08 
QuestionGreat article for beginers on WebService Pin
Rohcode19-Feb-15 23:51
Rohcode19-Feb-15 23:51 
AnswerRe: Great article for beginers on WebService Pin
Anurag Sinha V10-Mar-15 20:52
Anurag Sinha V10-Mar-15 20:52 
Questioncomment Pin
pankajpandey111023-Dec-14 23:29
pankajpandey111023-Dec-14 23:29 
QuestionHow response captured in alert message with out sending request ? Pin
venkata chaitanya29-Oct-14 20:25
venkata chaitanya29-Oct-14 20:25 
Questiongreat Pin
Member 1070043031-Jul-14 0:41
Member 1070043031-Jul-14 0:41 
Questionwebservice sample with json Pin
Mehdipirmoradian21-Mar-14 12:39
Mehdipirmoradian21-Mar-14 12:39 
Questionvery nice article for beginers Pin
sunneil chy16-Nov-13 7:55
sunneil chy16-Nov-13 7:55 
QuestionVery helpful Pin
Member 1005074219-Sep-13 19:59
Member 1005074219-Sep-13 19:59 
AnswerRe: Very helpful Pin
Anurag Sinha V19-Sep-13 20:41
Anurag Sinha V19-Sep-13 20:41 
GeneralRe: Very helpful Pin
Member 1005074219-Sep-13 23:28
Member 1005074219-Sep-13 23:28 
GeneralRe: Very helpful Pin
Anurag Sinha V20-Sep-13 1:25
Anurag Sinha V20-Sep-13 1:25 
QuestionHow to use for Windows phone 7,8 apps? Pin
SagarAnand01526-Aug-13 10:01
professionalSagarAnand01526-Aug-13 10:01 
AnswerRe: How to use for Windows phone 7,8 apps? Pin
Anurag Sinha V27-Aug-13 22:37
Anurag Sinha V27-Aug-13 22:37 
QuestionSecurity Error Pin
kryz_rock21-Aug-13 10:17
kryz_rock21-Aug-13 10:17 
AnswerRe: Security Error Pin
Anurag Sinha V21-Aug-13 18:47
Anurag Sinha V21-Aug-13 18:47 
GeneralRe: Security Error Pin
kryz_rock22-Aug-13 4:19
kryz_rock22-Aug-13 4:19 
QuestionThis was just what I was looking for. Pin
rleonard457724-May-13 8:27
rleonard457724-May-13 8:27 
GeneralThank you Pin
Vunnam2720-May-13 18:00
Vunnam2720-May-13 18:00 
GeneralRe: Thank you Pin
Anurag Sinha V20-May-13 21:31
Anurag Sinha V20-May-13 21:31 
QuestionGood artical simply enough for beginner Pin
Member 58993612-Apr-13 22:59
Member 58993612-Apr-13 22:59 
AnswerRe: Good artical simply enough for beginner Pin
Anurag Sinha V2-Apr-13 23:38
Anurag Sinha V2-Apr-13 23:38 
QuestionASMX is NOT in use any more Pin
sukumarraju1-Mar-13 3:31
sukumarraju1-Mar-13 3:31 
AnswerRe: ASMX is NOT in use any more Pin
Anurag Sinha V1-Mar-13 4:49
Anurag Sinha V1-Mar-13 4: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.