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

Consuming .NET Web Services Using the XMLHTTP Protocol

Rate me:
Please Sign up or sign in to vote.
3.44/5 (7 votes)
9 Feb 2008CPOL4 min read 71.4K   26   7
This article explains how to call a Web Service method using the XmlHttp protocol encapsulated by the XmlHttpRequest object.

Introduction

This article explains how to call a Web Service method using the XmlHttp protocol encapsulated by the XmlHttpRequest object.

Background

The XmlHttpRequest object was available as an ActiveX control in earlier versions of Internet Explorer (version 5.0 and 6.0), and you had to create this object as below:

C#
var myReq = new ActiveXObject("Microsoft.XMLHTTP");

Now, with IE 7, you can create an instance of the XmlHttpRequest object like this:

C#
var myReq = new XMLHttpRequest;

Introduction to XmlHttpRequest

The XmlHttpRequest object is supported in Internet Explorer 7. It is available in the window property of the IE browser. Using this object, you can make XML requests via HTTP. This object is the back-bone of Microsoft’s AJAX (Asynchronous Java and XML) technology to perform callbacks to the server on clients’ requests.

With the XMLHttpRequest object, Microsoft Internet Explorer clients can retrieve and submit XML data directly to a Web Server without reloading the page. On receiving XML content from the server, you can convert the XML data into readable HTML content, using the client-side XML DOM or XSLT.

Properties of the XmlHttpRequest object

Property

Description

onreadystatechange

Sets or retrieves the event handler for asynchronous requests.

readyState

Retrieves the current state of the request operation.

responseBody

Retrieves the response body as an array of unsigned bytes.

responseText

Retrieves the response body as a string.

responseXML

Retrieves the response body as an XML Document Object Model (DOM) object.

Status

Retrieves the HTTP status code of the request.

statusText

Retrieves the friendly HTTP status of the request.

Methods of the XmlHttpRequest object

Method

Description

abort

Cancels the current HTTP request.

getAllResponseHeaders

Returns the complete list of response headers.

getResponseHeader

Returns the specified response header.

open

Assigns method, destination URL, and other optional attributes of a pending request.

send

Sends an HTTP request to the server and receives a response.

setRequestHeader

Adds custom HTTP headers to the request.

Sample request using XMLHTTP to get an XML file

Open Visual Studio 2008 and create a new web site. Add a new XML file named “books.xml” to the website. Add a new web page to the site and place a HTML button control on the page. Tap the source tab below to view the markup. Modify the source by adding the following script written in JavaScript.

JavaScript
<script type="text/javascript" language="javascript"> 
var myReq = new XMLHttpRequest(); 
function getBooks() 
{ 
  if (window.XMLHttpRequest) 
  { 
    var url = "http://localhost:49216/WebXmlHttpDemo/books.xml" 
    myReq.open("GET", url, false) 
    myReq.send(); 
    alert(myReq.responseXML.xml); 
  } 
}

Remember to call this method in the onclick event of the button:

HTML
<input id="Button1" type="button" 
   value="Show Books" onclick="getBooks() " />

Consuming Web Services using XmlHttpRequest

The XmlHttpRequest object can be used to call even web service methods. In the Open method of the object, set the async flag as true and set the onreadystatechange property to a function. When you make a request to the Web Service method asynchronously, the function you specified is called back by XmlHttpRequest, reporting the status of the request. In this callback method, you can pass the input parameters for the Web Service method and invoke the method to get the results.

Now, let me explain how to consume a Web Service asynchronous flag set to true. Note that the Web Service method invocation involves multiple request-response SOAP messages and there is only a slighter possibility to execute web methods synchronously.

For testing purposes, a Web Service (.asmx) is added to the existing web site. To do so, in the website menu, select Add New Item and find the Web Service class in the dialog shown. Name the Web Service as SomeService.

C#
[WebService(Namespace = "http://localhost:49216/WebXmlHttpDemo/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
public class SomeService : System.Web.Services.WebService { 
    [WebMethod] 
    public string ReverseTheString(string s) { 
        string outText = "";
        char[] letters = new char[s.Length];
        s.CopyTo(0, letters, 0,s.Length);
        Array.Reverse(letters);
        foreach (char c in letters)
            outText += c; 
        return outText; 
    }
    [WebMethod] 
    public string GetTimeString() 
    {
        return DateTime.Now.ToLongTimeString(); 
    }

In the above Web Service, there are two web methods namely ReverseTheString that takes a string as input parameter and returns the reversed string as a result, and GetTimeString that returns the current time on the server side.

Calling a Web Service method with no input parameters

To consume the above Web Service from a web page, add an HTML button (ID=Button1) and a TextArea control to the web page. In the markup of the page, write the following script. It calls the GetTimeString method defined in the SomeService class.

JavaScript
<script type="text/javascript" language="javascript"> 
var myReq = new XMLHttpRequest(); 
function callWSMethod1() 
{ 
    if (window.XMLHttpRequest) 
    { 
        var url = "http://localhost:49216/WebXml" + 
                  "HttpDemo/SomeService.asmx?op=GetTimeString" 
        myReq.onreadystatechange = checkStatus1;
        // true indicates asynchronous request  
        myReq.open("GET", url, true);
        myReq.send(); 
    } 
} 
function CheckStatus1() 
{ 
    if (myReq.readyState == 4) // Completed operation 
    { 
        myReq.open("POST", 
          "http://localhost:49216/WebXmlHttpDemo/" + 
          "SomService.asmx/GetTimeString", false); 
        myReq.send(); 
        form1.TextArea1.value = oReq.responseText; 
    } 
} 
</script> 

Be sure to call the method CallWSMethod1 in the onclick event of button1.

HTML
<form id="form1" runat="server"> 
<div> 
<input id="Button1" type="button" 
  value="Get Time" onclick="callWSMethod1() " /><br /> 
<textarea id="TextArea1" name="S1"></textarea> 
</div> 
</form> 

Output:

xmlhttp1.jpg

Calling a Web Service method with input parameters

To consume the above Web Service from a web page, add an HTML button (ID=Button2). In the markup of the page, write the following script to call the ReverseTheString method defined in the SomeService class.

JavaScript
<script type="text/javascript" language="javascript"> 
var myReq = new XMLHttpRequest(); 
function callWSMethod2() 
{ 
    if (window.XMLHttpRequest) 
    { 
        var url = "http://localhost:49216/WebXmlHttpDemo/" + 
            "SomeService.asmx/ReverseTheString?someText="; 
        url += form1.Text1.value; 
        myReq.onreadystatechange = checkStatus2; 
        myReq.open("GET", url, true); 
    } 
} 
function CheckStatus2() 
{ 
    if (myReq.readyState == 4) 
    { 
        form1.TextArea1.value = myReq.responseXML.xml; 
    } 
} 
</script> 

Be sure to call the method CallWSMethod2 in the onclick event of Button2.

XML
<input id="Button2" type="button" 
    value="Reverse The String" onclick="callWSMethod2() " /><br /> 

Before running the page, add the following settings in the Web.Config file to enable the HTTP-GET and HTTP-POST methods in your website.

XML
<webServices> 
<protocols> 
<add name="HttpGet"/> 
<add name="HttpPost"/> 
</protocols> 
</webServices> 

Output:

xmlhttp2.jpg

These XML outputs can be presented in a much cleaner way using XSLT or by parsing them with the XML DOM object model.

Summary

This article explained the basics of the XmlHttpRequest object and showed how you can use it to call Web Service methods asynchronously. The real power and benefits of XmlHttpRequest lies in its usage and implementation in AJAX, Mozilla Development, and other technologies.

License

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


Written By
Founder BB Systems CIT-GPNP
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Kagan Agun2-Mar-15 19:33
Kagan Agun2-Mar-15 19:33 
GeneralMy vote of 2 Pin
Nisarg Desai26-Feb-14 18:05
Nisarg Desai26-Feb-14 18:05 
QuestionCode not working Pin
tej narayan maurya9-Jan-13 20:10
tej narayan maurya9-Jan-13 20:10 
I tried this code it is not working
it is showing network error in myReq.send();
QuestionCode not working Pin
Member 83707622-Jul-12 15:03
Member 83707622-Jul-12 15:03 
Generalthe attached zip file only contans the .sln file Pin
Stoj9-Jul-08 2:47
Stoj9-Jul-08 2:47 
GeneralAny help for Firefox browser Pin
vvv shah3-Apr-08 2:34
vvv shah3-Apr-08 2:34 
GeneralRe: Any help for Firefox browser Pin
Balamurali Balaji3-Apr-08 4:56
Balamurali Balaji3-Apr-08 4:56 

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.