Click here to Skip to main content
11,574,503 members (54,740 online)
Click here to Skip to main content

Calling WCF Services using jQuery

, 2 Dec 2010 CPOL 274.8K 13.3K 127
Rate this:
Please Sign up or sign in to vote.
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

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

Service.cs

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

[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

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

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

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

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.

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

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)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)


Hey, I am Pranay Rana, working as a ITA in 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:



You may also be interested in...

Comments and Discussions

 
GeneralVery nice Pin
i_am_luc23hrs 46mins ago
memberi_am_luc23hrs 46mins ago 
QuestionThe blog post code is perfect. Thank you!! However... Pin
Member 116728207-May-15 8:23
memberMember 116728207-May-15 8:23 
QuestionCalling 3 services in single javascript ajax get function Pin
waleed ahmed wadkar6-Jul-14 22:16
memberwaleed ahmed wadkar6-Jul-14 22:16 
QuestionCode not working Pin
OsiKosi6-May-14 5:56
memberOsiKosi6-May-14 5:56 
Questionconsuming WCF from MVC web app through jQuery Pin
sharma-anurag3-Mar-14 6:34
membersharma-anurag3-Mar-14 6:34 
AnswerRe: consuming WCF from MVC web app through jQuery Pin
Pranay Rana6-Mar-14 0:38
professionalPranay Rana6-Mar-14 0:38 
QuestionHello, Pin
santosh panchal15-Jan-14 1:23
membersantosh panchal15-Jan-14 1:23 
Questionalling WCF Services using jQuery Pin
Braj Kishor24-Dec-13 0:39
memberBraj Kishor24-Dec-13 0:39 
SuggestionAsynchronous call to WebService / WCF using JQuery Pin
hemantrhtk10-Nov-13 19:48
memberhemantrhtk10-Nov-13 19:48 
GeneralThanks. but how to call GetData() Pin
Member 78161014-May-13 22:13
memberMember 78161014-May-13 22:13 
GeneralRe: Thanks. but how to call GetData() Pin
Sunasara Imdadhusen19-May-13 18:52
professionalSunasara Imdadhusen19-May-13 18:52 
GeneralRe: Thanks. but how to call GetData() Pin
Member 78161026-Sep-13 20:01
memberMember 78161026-Sep-13 20:01 
GeneralEasiest way to create and consume WCF Services in asp.net Pin
Lalit24rocks14-May-13 21:38
memberLalit24rocks14-May-13 21:38 
QuestionExcellent Pin
Jean Paul Abdilla6-May-13 11:01
memberJean Paul Abdilla6-May-13 11:01 
GeneralMy vote of 1 Pin
DotNetExpertsIL6-Mar-13 13:30
memberDotNetExpertsIL6-Mar-13 13:30 
Questionmaybe I'm not Politically correct ... Pin
DotNetExpertsIL4-Mar-13 14:30
memberDotNetExpertsIL4-Mar-13 14:30 
QuestionCode Incomplete Pin
nishantcop1-Mar-13 16:40
membernishantcop1-Mar-13 16:40 
QuestionWhat you are trying to exaplin here boss??? Pin
Kanaparthi Prasad27-Oct-12 20:40
memberKanaparthi Prasad27-Oct-12 20:40 
AnswerRe: What you are trying to exaplin here boss??? Pin
Pranay Rana28-Oct-12 19:56
memberPranay Rana28-Oct-12 19:56 
QuestionCalling a WCF Service using JQuery Pin
Ganeshcse16-Aug-12 19:12
memberGaneshcse16-Aug-12 19:12 
GeneralMy vote of 3 Pin
Ganeshcse16-Aug-12 19:08
memberGaneshcse16-Aug-12 19:08 
GeneralThanks Pin
LeeSmith2416-Jun-12 8:03
memberLeeSmith2416-Jun-12 8:03 
GeneralMy vote of 5 Pin
Vishal Varshney11-Jun-12 9:30
memberVishal Varshney11-Jun-12 9:30 
QuestionWhy GET for GetData and POST for GetUser? Pin
gbelzile197912-Apr-12 8:11
membergbelzile197912-Apr-12 8:11 
QuestionNo Transport Error Pin
parminderdeo29-Nov-11 2:54
memberparminderdeo29-Nov-11 2:54 
GeneralHi Pin
mskrishna4416-Jun-11 2:39
membermskrishna4416-Jun-11 2:39 
GeneralMy vote of 5 Pin
vladisvit20-Feb-11 0:01
membervladisvit20-Feb-11 0:01 
GeneralMy vote of 5 Pin
saanj19-Jan-11 17:28
membersaanj19-Jan-11 17:28 
GeneralRe: My vote of 5 Pin
Pranay Rana19-Jan-11 23:36
memberPranay Rana19-Jan-11 23:36 
GeneralMy vote of 5 Pin
jayesh_lakhtariya16-Jan-11 22:27
memberjayesh_lakhtariya16-Jan-11 22:27 
GeneralRe: My vote of 5 Pin
Pranay Rana18-Jan-11 0:22
memberPranay Rana18-Jan-11 0:22 
GeneralMy vote of 5 Pin
Abdul Quader Mamun8-Jan-11 2:33
memberAbdul Quader Mamun8-Jan-11 2:33 
GeneralRe: My vote of 5 Pin
Pranay Rana18-Jan-11 0:21
memberPranay Rana18-Jan-11 0:21 
GeneralMy vote of 4 Pin
Jaleelali5-Jan-11 5:58
memberJaleelali5-Jan-11 5:58 
GeneralRe: My vote of 4 Pin
Pranay Rana19-Jan-11 23:37
memberPranay Rana19-Jan-11 23:37 
GeneralMy vote of 4 Pin
M Sheik Uduman Ali30-Dec-10 15:01
memberM Sheik Uduman Ali30-Dec-10 15:01 
GeneralRe: My vote of 4 Pin
Pranay Rana30-Dec-10 16:20
memberPranay Rana30-Dec-10 16:20 
QuestionHasn't this been done before in 2008 ? Pin
Member 456543330-Dec-10 2:37
memberMember 456543330-Dec-10 2:37 
AnswerRe: Hasn't this been done before in 2008 ? Pin
Pranay Rana30-Dec-10 16:20
memberPranay Rana30-Dec-10 16:20 
GeneralRe: Hasn't this been done before in 2008 ? Pin
Member 456543331-Dec-10 4:08
memberMember 456543331-Dec-10 4:08 
GeneralRe: Hasn't this been done before in 2008 ? Pin
Pranay Rana2-Jan-11 18:17
memberPranay Rana2-Jan-11 18:17 
GeneralMy vote of 5 Pin
Jalpesh Vadgama29-Dec-10 22:10
memberJalpesh Vadgama29-Dec-10 22:10 
GeneralRe: My vote of 5 Pin
Pranay Rana29-Dec-10 23:36
memberPranay Rana29-Dec-10 23:36 
GeneralMy vote for 5 Pin
Gaurav Dudeja India29-Dec-10 18:01
memberGaurav Dudeja India29-Dec-10 18:01 
GeneralRe: My vote for 5 Pin
Pranay Rana29-Dec-10 18:44
memberPranay Rana29-Dec-10 18:44 
GeneralMy vote of 5 Pin
abhishek pareek200923-Dec-10 2:57
memberabhishek pareek200923-Dec-10 2:57 
GeneralMy vote of 5 Pin
prasad0222-Dec-10 4:49
memberprasad0222-Dec-10 4:49 
GeneralRe: My vote of 5 Pin
Pranay Rana22-Dec-10 18:02
memberPranay Rana22-Dec-10 18:02 
GeneralMy vote of 5 Pin
Jalpesh Vadgama19-Dec-10 19:51
memberJalpesh Vadgama19-Dec-10 19:51 
Nice Job pranay.Keep doing it.
GeneralRe: My vote of 5 Pin
Pranay Rana19-Dec-10 20:42
memberPranay Rana19-Dec-10 20:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150624.2 | Last Updated 2 Dec 2010
Article Copyright 2010 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid