Freigeben über


How To Consume WCF Using AJAX Without ASP.NET

RESTful .NET - Build and Consume RESTful Web Services

How to consume WCF services directly from Html client? How to add AJAX-like functionally to application that does not natively support ASP.NET AJAX like classic ASP, ASP.NET 1.1, or PHP?

WCF that ships with .Net 3.5 provides capability to consume it from any JavaScript enabled client via XML or JSON encoding. There is new built in webHttpBinding that supports either JSON or XML encoded messages to be sent to WCF services.The functionality can dramatically improve performance and user experience.

This post summarizes the steps to create and consume basic WCF service using webHttpBinding binding.

Summary of Steps

  • Step 1 – Create WCF service.
  • Step 2 – Configure WCF end point.
  • Step 3 – Create JavaScript to invoke WCF service.
  • Step 4 – Test the solution.

Next section describes each and every step in details

Step 1 – Create WCF service

Open Visual Studio and create new WCF service project by choosing "WCF Service Application" template under "Web" project type. Name it Wcf2Ajax. Open IService1.cs file and create OperationContract as follows:

    1: [ServiceContract]
    2:  public interface IService1
    3:  {
    4:  
    5:      [OperationContract]
    6:      string Sum2Integers(int n1, int n2);

Open Service1.svc.cs file and add public method that accepts to integers and returns the sum of it. This is the functionality that will be exposed by the WCF service and consumed by JavaScript enabled client:

    1: public class Service1 : IService1
    2: {
    3:     public string Sum2Integers(int n1, int n2)
    4:     {
    5:         int result = num1 + num2;
    6:  
    7:         return result.ToString();
    8:     }

Step 2 – Configure WCF end point

Open web.config file and add <binding> section to <system.serviceModel section. Add <webHttpBinding> to binding section:

 <system.serviceModel>
  <bindings>
    <webHttpBinding>
      <binding name="AjaxBinding"/>
    </webHttpBinding>
  </bindings

Add AjaxBehavior to <behaviors> section to support WCF invocation via AJAX:

 <behaviors>
  <endpointBehaviors>
    <behavior name="AjaxBehavior">
      <enableWebScript/>
    </behavior>

Configure WCF service's endpoint to use newly created binding:

 <endpoint address="ajaxEndpoint" 
          behaviorConfiguration="AjaxBehavior" 
          binding="webHttpBinding" 
          bindingConfiguration="AjaxBinding" 
          contract="Wcf2Ajax.IService1">

Step 3 – Create JavaScript to invoke WCF service

Add Html file to the solution by right clicking on the solution node in solution explorer and choosing "New Item..." and then "HTML Page" template. Name it WCFConsumer.htm. Add few HTML controls - two text boxes to accept two integers, one pure HTML button to trigger WCF call, and <span> element to present the result:

 <input type="text" id="num1" />
<input type="text" id="num2" />
<br>
<input type="button" onclick="CallWcfAjax()" value="Call WCF via AJAX" />
Result <span id="result"></span>

Add <script> block to <header> section and add JavaSctip that builds HTTP request and wires invocation function to some event, say button click:

     <script type="text/javascript">
    function CallWcfAjax()
    {
        var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");

        var url = "Service1.svc/ajaxEndpoint/";
        url = url + "Sum2Integers";

        var body = '{"n1":';
        body = body + document.getElementById("num1").value + ',"n2":';
        body = body + document.getElementById("num2").value + '}';
          
        // Send the HTTP request
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Content-type", "application/json");
        xmlHttp.send(body);

        // Create result handler 
        xmlHttp.onreadystatechange= function X()
        {
        
             if(xmlHttp.readyState == 4)
             {
                  result.innerText = xmlHttp.responseText;
             }
        }
    }
    </script>

Step 4 – Test the solution

Build the solution and navigate to WCFConsumer.htm. Provide two integers to both text boxes and hit "Call WCF via Ajax" button. You should expect for result similar as depicted below:

image

Parse the result to your needs.

 

My related post

 

Related resources

Download Visual Studio 2008 project with the sample from my SkyDrive

 

Comments

  • Anonymous
    February 18, 2008
    Hi,is this working in Mozilla too?for me the Microsoft.XmlHttp is very strange?Isn't there a more 'standard'  way?:)Tamas
  • Anonymous
    February 18, 2008
    Good point, Tamas!The focus of the post is about server side - how WCF exposes itself to AJAX clients, but your comment is valid and very relevant.Any client that can issue such HTTP request can consume WCF services that exposes itself via webHttpBinding. I am not in the know how it is done with Mozila in "standard way", but in IE Microsoft.XmlHttp is the way to do. Search the web and you will find plenty code samples I am sure. Once you found the sample construct the following HTTP request using your code. I captured it using Fiddler. Make sure you substitute few details relevant to your environment.POST /Service1.svc/ajaxEndpoint/Sum2Integers HTTP/1.1Accept: /Accept-Language: en-usReferer: http://localhost.:56966/WCFConsumer.htmContent-Type: application/jsonUA-CPU: x86Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SU 3.011; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 3.5.21022; MS-RTC LM 8)Host: localhost.:56966Content-Length: 15Proxy-Connection: Keep-AlivePragma: no-cache{"n1":1,"n2":2}
  • Anonymous
    February 19, 2008
    Very interesting - but I wish you had written this post last week when I was trying to figure this out!!  What is the best way to secure these services (reasonably secure but not requiring a whole lot more Javascript code) so that unauthenticated requests are not accepted?
  • Anonymous
    February 19, 2008
    Nick!Great to hear you found it interesting. I am going to address security and other details, like JASON vs XML encoding, in my next posts.Basically speaking - there should be nothing special about authenticaion. In case of windows integrated or other type of authentication XmlHttp was used for long ago before WCF and it "knows" how to pick up on right athentication scheme already in use. No extra JavaScript is requred. Do you struggle with any particula issue that you want to share? Would love to hear about it.Thanksalikl
  • Anonymous
    February 20, 2008
    概述春节后的第一期推荐系列文章,共有10篇文章:1.ASP.NETMVCExampleApplicationoverNorthwindwiththeEntityFramework...
  • Anonymous
    February 20, 2008
    概述 春节后的第一期推荐系列文章,共有10篇文章: 1.ASP.NETMVCExampleApplicationoverNorthwindwiththeEntityFr...
  • Anonymous
    April 17, 2008
    This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case
  • Anonymous
    April 18, 2008
    Great post! Can you put up an example or do you have and example of calling a svc from a different domain?Thank you
  • Anonymous
    April 19, 2008
    This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case
  • Anonymous
    May 23, 2008
    If you're building Web services or if you're implementing SOA on the Microsoft platform , then you're
  • Anonymous
    October 28, 2008
    &#160; &#160;&#160;&#160; AJAX improves significantly both user experience and performance. It can be