CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Consuming .NET Web Services using XMLHTTP protocol

By balamurali balaji
Posted On Mar 24,2008
Article Rating:
Be first to rate
this article.
No of Comments: 8
Category: WebServices
Print this article.

Consuming .NET Web Services using XMLHTTP protocol

 

This article explains how to call a web service method using XmlHttp protocol encapsulated by javascript XmlHttpRequest object.

 

Background

 

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:

 

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

 

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

var myReq = new XMLHttpRequest;

 

Introduction to XmlHttpRequest

 

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

 

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 XML data into readable HTML content, using the client-side XML DOM or XSLT.

 

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

 

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

 

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

 

Consuming Web Services using  XmlHttpRequest

 

XmlHttpRequest  object can be used to call even the web service methods. In the open method of the object, set the async flag as true; set the onreadystatechange property to a function. When you make a request to the webservice 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 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, webservice (.asmx) is added to the existing web site. To do so, In the WebSite menu, Select Add New Item and find the WebService Class in the dialog shown. Name the WebService as SomeService.

 

[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; GetTimeString returns the current time on the server side.

 




Calling a Web Service method with no input parameters

To consume the above web service from the web page, add a HTML button(id=Button1) and 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.

 

    <script type="text/javascript" language="javascript">

    var myReq = new XMLHttpRequest();

    function callWSMethod1()

    {

        if (window.XMLHttpRequest)

            {

                var url = "http://localhost:49216/WebXmlHttpDemo/SomeService.asmx?op=GetTimeString"

                myReq.onreadystatechange = checkStatus1;

                myReq.open("GET", url, true); // true indicates asynchronous request

                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.

 

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

 

Calling a Web Service method with input parameters

 

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

 

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

 

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

 

Output:

 

 

Before running the page, add the following settings in the Web.Config file to enable Http-Get and Http-Post methods in your website.

 

  <webServices>

    <protocols>

      <add name="HttpGet"/>

      <add name="HttpPost"/>

    </protocols>

</webServices>

 

Downloads

Download Source

Summary

 

This article explained the basics of 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, SilverLight and other technologies.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Don't you feel this
Don't you feel this method of pnforrmieg an XHR request is a bit dated now with all the frameworks such as mootools and jquery that handle this sort of thing for you? Don't get me wrong, this is how I originally learned how to perform XHR requests, but I feel frameworks are the way to go now.
Did not work
Calling a Web Service method with no input parameters did not work for my no way.
I tried everything to get this to work. Shame but thanks anyway.
Special Thanks
Thanks a lot.
last 6 line of your Article save several hours of my time.
Parameterised Call
Hi mahesh,

I should work as in the code I wrote when you also set the configuration section as mentioned. It uses GET method and the parameter is passed along with the URL.

The code you specified uses POST method which would require parameters not passed via url.

Hope this helps.

-Bala
With Parameters not working
The section which says 'Calling web service with parameters ' will work with the following modification only

var url = "http://localhost:49216/WebXmlHttpDemo/SomeService.asmx

myReq.onreadystatechange = CheckStatus1;
myReq.open("POST", url, true);
myReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var param=form1.Text1.value;
myReq.send("someText=param");
Always User's Choice
I agree that it's user's choice. Just seems like it would have been a better article had you explained more about how to use this stuff, or why you would use it. The other article indicates that JSON from webservices is new in .NET35. This is not true, it's been around for a long time before .NET 35, it's just more known as an option in the marketing materials now for the framework.
User's Choice
Yes, you are correct in one way. .NET web services return plain XML output and on the client side one need to parse or use XSL to represent results in required format. Microsoft uses JSON for web services and WCF in the 3.5 version of .net framework and that would give us more control over formatting and transporting data through JSON. Though this article do not focus on how to display the results, it dealts with how to make quick calls from client browser to the webservice methods on the server side and the client has many ways such as using XSL, XPath, or saving it to a file. It is left to the users' choice. Please read my another article related to Web services and AJAX: http://www.codedigest.com/Articles/ASPNET/52_ASPNET_35_AJAX_and_WebServices__.aspx
Isn't this a step backwards?
The whole reason why most implementations of AJAX utilities leave off the "X" portion in favor of JSON, is that consuming XML on the client side is a pain. In the example above, nothing was really done with the results of the web service aside from displaying the xml returned. What would it take to only display what you asked for, which was Hello World! spelled backwards? Now you have to parse the xml on the client side. Microsoft is even a proponent of JSON in how they've instrumented ASMX pages to optionally render JSON instead of SOAP for client side calls, because of the simplicity of parsing the response on the client browser. That said, maybe you can append an example of how you'd parse that result, and stick the !dlroW olleH by itself in a text box.