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

Calling WCF Services using jQuery

Rate me:
Please Sign up or sign in to vote.
4.76/5 (85 votes)
2 Dec 2010CPOL3 min read 507.7K   17.1K   142   104
A guide on how to call Windows Communication Foundation services using jQuery

Introduction

This article illustrates how to call Windows Communication Foundation (WCF) services from your jQuery client code, and points out where special care is needed. Before you start reading and following this article, first read this blog entry which describes how to create a WCF service: Create, Host and Consume a WCF Service.

Step 1

Once you are done with creating the WCF service, you need to specify the attributes on the server type class for ASP.NET compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features. By setting compatibility mode, the WCF service will have to be hosted on IIS and communicate with its client application using HTTP.

Read more about this in detail here: WCF Web HTTP Programming Object Model.

The following line of code sets ASP.NET compatibility mode

C#
[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    // Your code comes here
}

Service.cs

C#
[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


    public string[] GetUser(string Id)
    { 
        return new User().GetUser(Convert.ToInt32(Id));
    }
}

public class User
{

    Dictionary<int, string> users = null;
    public User()
    {
        users = new Dictionary<int, string>();
        users.Add(1, "pranay");
        users.Add(2, "Krunal");
        users.Add(3, "Aditya");
        users.Add(4, "Samir");
    }

    public string[] GetUser(int Id)
    {
        var user = from u in users
                   where u.Key == Id
                   select u.Value;

        return user.ToArray<string>();
    }

}

Step 2

Next you need to specify attributes at operation level in the service contract file for each method or operation. To do this, decorate the method with WebInvoke, which marks a service operation as one that responds to HTTP requests other than GET. Accordingly, your operational level code in the contract file will be as follows:

C#
[OperationContract]
[OperationContract]
[WebInvoke(Method = "POST", 
 BodyStyle = WebMessageBodyStyle.Wrapped,
 ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);

As you can see in the code, sub-attributes having values to support calling via jQuery are marked with Method=post, so data gets posted to the service via a POST method.

ResponseFormat = WebMessageFormat.Json indicates that data is returned in JSON format.

IService.cs

C#
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
     ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

    [OperationContract]
    [WebInvoke(Method = "POST", 
     BodyStyle = WebMessageBodyStyle.Wrapped, 
     ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);
}

Step 3

You need to change the default configuration created by Visual Studio in Web.Config file for WCF services, so that it works with the HTTP protocol request send by jQuery client code.

XML
<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" 
        contract="IService" behaviorConfiguration="EndpBehavior"/>
   </service>
  </services>
</system.serviceModel>

As you can see in above config file, the EndPoint setting is changed, and EndPointBehaviors added to support WEBHTTP requests.

Note: Endpoint settings done in the config works in conjunction with the WebInvoke attribute of the operation and the compatibility attribute set in ServiceType to support HTTP requests sent by jQuery.

Step 4

To consume a web service using jQuery, that is to make a call to the WCF service, you either use jQuery.ajax() or jQuery.getJSON(). In this article I used the jQuery.ajax()method.

To set the request, first define a variable. This will be helpful when you are calling multiple methods and creating a different js file to call the WCF service.

JavaScript
<script type="text/javascript">

    var Type;
    var Url;
    var Data;
    var ContentType;
    var DataType;
    var ProcessData;

The following function initializes variables which are defined above to make a call to the service.

JavaScript
function WCFJSON() {
    var userid = "1";
    Type = "POST";
    Url = "Service.svc/GetUser";
    Data = '{"Id": "' + userid + '"}';
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; varProcessData = true; 
    CallService();
}

The CallService function sends requests to the service by setting data in $.ajax.

JavaScript
// Function to call WCF  Service       
function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function(msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result) {
    alert('Service call failed: ' + result.status + '' + result.statusText);
    Type = null;
    varUrl = null;
    Data = null; 
    ContentType = null;
    DataType = null;
    ProcessData = null;
}

Note: The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.

JavaScript
function ServiceSucceeded(result) {
    if (DataType == "json") {
        resultObject = result.GetUserResult;
        
        for (i = 0; i < resultObject.length; i++) {
            alert(resultObject[i]);
        }
            
    }
        
}

function ServiceFailed(xhr) {
    alert(xhr.responseText);

    if (xhr.responseText) {
        var err = xhr.responseText;
        if (err)
            error(err);
        else
            error({ Message: "Unknown server error." })
    }
    
    return;
}

$(document).ready(
    function() {
        WCFJSON();
    }
);
</script>

Summary

It is easy to call a WCF service from your client code you; just need to set your WCF service to serve requests through the HTTP protocol and set your client to consume it via the HTTP protocol.

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralMy vote for 5 Pin
Gaurav Dudeja India29-Dec-10 18:01
Gaurav Dudeja India29-Dec-10 18:01 
GeneralRe: My vote for 5 Pin
Pranay Rana29-Dec-10 18:44
professionalPranay Rana29-Dec-10 18:44 
GeneralMy vote of 5 Pin
abhishek pareek200923-Dec-10 2:57
abhishek pareek200923-Dec-10 2:57 
GeneralMy vote of 5 Pin
prasad0222-Dec-10 4:49
prasad0222-Dec-10 4:49 
GeneralRe: My vote of 5 Pin
Pranay Rana22-Dec-10 18:02
professionalPranay Rana22-Dec-10 18:02 
GeneralMy vote of 5 Pin
Jalpesh Vadgama19-Dec-10 19:51
Jalpesh Vadgama19-Dec-10 19:51 
GeneralRe: My vote of 5 Pin
Pranay Rana19-Dec-10 20:42
professionalPranay Rana19-Dec-10 20:42 
GeneralMy vote of 5 Pin
Enrique Albert19-Dec-10 18:29
Enrique Albert19-Dec-10 18:29 
GeneralRe: My vote of 5 Pin
Pranay Rana19-Dec-10 20:41
professionalPranay Rana19-Dec-10 20:41 
GeneralMy vote of 5 Pin
Avi Farah18-Dec-10 16:57
Avi Farah18-Dec-10 16:57 
GeneralRe: My vote of 5 Pin
Pranay Rana19-Dec-10 20:43
professionalPranay Rana19-Dec-10 20:43 
GeneralMy vote of 5 Pin
Peace ON15-Dec-10 5:50
Peace ON15-Dec-10 5:50 
GeneralRe: My vote of 5 Pin
Pranay Rana15-Dec-10 7:58
professionalPranay Rana15-Dec-10 7:58 
GeneralMy vote of 5 Pin
shyam22114-Dec-10 22:33
shyam22114-Dec-10 22:33 
GeneralMy vote of 5 Pin
tushar22914-Dec-10 20:08
tushar22914-Dec-10 20:08 
GeneralRe: My vote of 5 Pin
Pranay Rana14-Dec-10 20:14
professionalPranay Rana14-Dec-10 20:14 
GeneralMy vote of 5 Pin
Brij14-Dec-10 19:39
mentorBrij14-Dec-10 19:39 
GeneralRe: My vote of 5 Pin
Pranay Rana14-Dec-10 20:13
professionalPranay Rana14-Dec-10 20:13 
GeneralMy vote of 5 Pin
tantod ravindrasingh14-Dec-10 5:08
tantod ravindrasingh14-Dec-10 5:08 
GeneralRe: My vote of 5 Pin
Pranay Rana14-Dec-10 20:15
professionalPranay Rana14-Dec-10 20:15 
GeneralMy vote of 5 Pin
Trupti patolia14-Dec-10 5:00
Trupti patolia14-Dec-10 5:00 
GeneralRe: My vote of 5 Pin
Pranay Rana14-Dec-10 20:16
professionalPranay Rana14-Dec-10 20:16 
GeneralMy vote of 5 Pin
jayesh_lakhtariya14-Dec-10 3:42
jayesh_lakhtariya14-Dec-10 3:42 
GeneralRe: My vote of 5 Pin
Pranay Rana14-Dec-10 20:17
professionalPranay Rana14-Dec-10 20:17 
GeneralMy vote of 5 Pin
shyam2218-Dec-10 22:32
shyam2218-Dec-10 22:32 

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.