Click here to Skip to main content
15,505,080 members
Articles / Web Development / ASP.NET
Posted 10 Jul 2011


51 bookmarked

Calling Cross Domain WCF service using Jquery/JavaScript

Rate me:
Please Sign up or sign in to vote.
4.74/5 (21 votes)
18 Jul 2011CPOL5 min read
Calling Cross Domain WCF service using Jquery/JavaScript


This article is about to call the cross domain WCF service from your page, i.e., calling WCF service hosted on one domain and calling the service form jquery/JavaScript of page which is hosted on some other domain.

But before we start, it's better to get understand about the format of the data get exchange from one server to another.

JSONP - JSON with Padding

Ajax allows to get data in the background without interfering with the display. Ajax call done by using XMLHttpRequest object allows the client side JavaScript code to make HTTP connections.
But Ajax call does not allow to get data from cross-domain because of restrictions imposed by the browser. Security error gets issued when requesting data from another domain. One way to avoid security errors is to control remote server where data resides and every request goes to the same domain. That gives rise to the question, what's the fun if data comes from own server only? What to do if data is required to get from the other server?

There is one way to come out from this limitation - to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes. It works because the same-origin policy doesn't prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP or "JSON with padding" is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from cannot normally connect to or communicate with a server other than An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve JavaScript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

Calling Cross Domain WCF service

Now in the following discussion, I am going to show you how easily you can call the WCF service hosted on the other domain from the page hosted on the other domain.
Following is list of articles you should look at first before moving further:

To start, first create a new solution and Add new Project which is WCF service and follow the below steps.

Step 1

In the new release of .NET 4.0, the WCF developer team added support for JSONP. There is a new property added which enables to call WCF service from other domain by setting it to true.
CrossDomainScriptAccessEnabled - Gets or sets a value that determines if cross domain script access is enabled.

Change your WCF service config file as below:

    <compilation debug="true" targetframework="4.0">
    <authentication mode="None">
    <modules runallmanagedmodulesforallrequests="true">
    <servicehostingenvironment aspnetcompatibilityenabled="true">
        <standardendpoint crossdomainscriptaccessenabled="true">

As you can see in the above config code, I have set crossdomainscriptaccessenabled to true and aspnetcompatibilityenabled to true so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features.

Step 2

SVC file of the service should be as below:

<%@ ServiceHost Language="C#" Debug="true" 
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"  %> 

Don't forget to add Factory attribute because it causes an error if you remove it. Following are the reasons to add Factory attribute:

  1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
  2. This is useful when we need to implement the event handlers for opening and closing the service.
  3. WCF provides ServiceFactory class for this purpose.

Step 3

CS file for the WCF file is:

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
    public class Customer
        public string Name;

        public string Address;

    [ServiceContract(Namespace = "JsonpAjaxService")]
    [AspNetCompatibilityRequirements(RequirementsMode =   
    public class Service1
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public Customer GetCustomer()
            return new Customer() { Name = "Pranay", Address = "1 Ahmedabad" };

As you can see in the above code, I have created Service class which is a service contract which serves data and Customer class is DataContract which get served as response.
In the service class, GetCustomer method services data in Json format.
Once the WCF service is created, to move further Add new project >> ASP.NET service. So that both the WCF service and website run on two different ones like are both hosted on different domains.
There are two solutions to call the Cross Domain WCF service.

Solution 1: Call WCF service by using JQuery

Jquery already has support to handle the jsonp. Jquery library provided function ajax and getJson which can allow to call the WCF service which sends jsonp data in response.

CallService - Generic function is used to call the WCF service, which gets called by other JavaScript function to get and display data.

var Type;
        var Url;
        var Data;
        var ContentType;
        var DataType;
        var ProcessData;
        var method;
        //Generic function to call WCF  Service
        function CallService() {
                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 Successful service call
                error: ServiceFailed// When Service call fails

ServiceFailed - gets called when call to service fails.

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

ServiceSucceeded - gets called when the service successfully returns a response. As you can see in the function, I am checking DataType is jsonp which is just to demonstrate that service is returning jsonp data.

function ServiceSucceeded(result) {
            if (DataType == "jsonp") {
                    resultObject = result.GetEmployeeResult;
                    var string = result.Name + " \n " + result.Address ;

GetEmployee - is a function that gets called to request data from WCF service hosted on other domain. As you can see in code, DataType value gets set to jsonp.

function GetEmployee() {
            var uesrid = "1";
            Type = "GET";
            Url = "http://localhost:52136/Service1.svc/GetCustomer"; 
            DataType = "jsonp"; ProcessData = false;
            method = "GetCustomer";

         function () {

Solution 2: Call WCF Service by JavaScript

To call the service using JavaScript, make use of ScriptManager:

<asp:scriptmanager id="ScriptManager1" runat="server">
           <asp:servicereference path="http://localhost:52136/Service1.svc">

In the above code, I set the servicereference to the WCF service hosted on other domain.

makeCall - function that gets called to request data from WCF service hosted on another domain.

function makeCall() {
                      var proxy = new JsonpAjaxService.Service1();
                     proxy.GetCustomer(onSuccess, onFail, null);

onSuccess - is called when the result from the service call is received and displays data.

function onSuccess(result) {
                     alert( result.Name + " " +result.Address);

onFail - is called if the service call fails.

function onFail(){


So after the addition to the special property by the WCF team, it's quite easy to call cross domain WCF service.



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


Comments and Discussions

Questioncross domain not working Pin
Member 775659122-Jul-15 1:29
Member 775659122-Jul-15 1:29 
QuestionNo SVC file in my project Pin
Girish Chawrai8-Feb-15 18:53
Girish Chawrai8-Feb-15 18:53 
Question'standardEndpoints' element is not supported. Pin
Rasmita Dash18-Aug-14 20:05
Rasmita Dash18-Aug-14 20:05 
QuestionNeed help in implementing WCF Service using JSON Pin
kumar thrishool15-Aug-14 1:01
kumar thrishool15-Aug-14 1:01 
QuestionMy Vote is 5 Pin
alpergunay16-Aug-13 3:14
alpergunay16-Aug-13 3:14 
GeneralThanks Allot Pin
Usman Khalid Butt21-Jun-13 2:22
Usman Khalid Butt21-Jun-13 2:22 
GeneralMy vote of 5 Pin
Member 811245513-Jun-13 2:36
Member 811245513-Jun-13 2:36 
GeneralMy vote of 5 Pin
Member 477261317-May-13 2:51
Member 477261317-May-13 2:51 
QuestionSending a request&response using .net Pin
Member 91711281-May-13 3:27
Member 91711281-May-13 3:27 
QuestionGreat article .. looks very straight forward and promising. Pin
CyberPine EducationalMedia27-Jan-13 3:00
CyberPine EducationalMedia27-Jan-13 3:00 
CyberPine EducationalMedia27-Jan-13 7:16
CyberPine EducationalMedia27-Jan-13 7:16 
QuestionNot working Pin
Praveen Adigoppula20-Sep-12 22:46
Praveen Adigoppula20-Sep-12 22:46 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey27-Mar-12 2:11
professionalManoj Kumar Choubey27-Mar-12 2:11 
QuestionCross-domain issue Pin
mehrdadc4823-Dec-11 20:27
mehrdadc4823-Dec-11 20:27 
QuestionNo Transport Error when Call to WCF service from JQuery Pin
parminderdeo1-Dec-11 2:56
parminderdeo1-Dec-11 2:56 
QuestionCustomer....Employee??? Pin
Noel Fernandes17-Nov-11 20:25
Noel Fernandes17-Nov-11 20:25 
SuggestionReduce global scope in Javascript code Pin
Rupesh Kumar Tiwari13-Oct-11 11:59
Rupesh Kumar Tiwari13-Oct-11 11:59 
GeneralRe: Reduce global scope in Javascript code Pin
Pranay Rana16-Oct-11 19:04
professionalPranay Rana16-Oct-11 19:04 
QuestionIs it only for WCF written in .net 4 Pin
Rupesh Kumar Tiwari12-Oct-11 11:37
Rupesh Kumar Tiwari12-Oct-11 11:37 
QuestionJSONP with Post Pin
Member 342287726-Jul-11 18:14
Member 342287726-Jul-11 18:14 
SuggestionMany Suggestions Pin
thatraja18-Jul-11 7:52
professionalthatraja18-Jul-11 7:52 
GeneralRe: Many Suggestions Pin
Pranay Rana18-Jul-11 20:39
professionalPranay Rana18-Jul-11 20:39 

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.