Home > JScript > Consuming WCF service from Jscript using JQuery

Consuming WCF service from Jscript using JQuery

I recently got a requirement to host a WCF service in Azure and consume it client side using Jscript.

In this article, I am providing details on how to consume WCF service from Jscript with the help of JQuery.

In below example, service is a simple “Products.svc” contain 1 method “GetProducts()” and returns List<Product> (“Product” is custom class)

WCF Service

  • Service Contract (IProductService.cs)

[ServiceContract(Namespace = “http://ABCproducts&#8221;,

Name = “IProductService”,

SessionMode = SessionMode.NotAllowed,

ProtectionLevel = ProtectionLevel.None)]

public interface IProductService{

[OperationContract]

[WebInvoke(

Method = “POST”,

BodyStyle = WebMessageBodyStyle.Wrapped,

RequestFormat = WebMessageFormat.Json,

ResponseFormat = WebMessageFormat.Json)]

List<Product> GetProducts();

}

[DataContract]

public class Product{

string id = string.Empty;

string name = string.Empty;

[DataMember]

public string ProductId{

get { return id; }

set { id = value; }

}

[DataMember]

public string ProductName{

get { return name; }

set { name = value; }

}

}

  • Service (ProductService.svc)

public List<Product> GetProducts(){

List<Product> products = new List<Product>();

Product P1 = new Product();

P1.Id = “1”;

P1.Name = “Mango”;

Product P2 = new Product();

P2.Id = “2”;

P2.Name = “Apple”;

products.Add(P1);

products.Add(P2);

return products;

}

  • Service Binding (Web.config)
    • Very important note is, the service endpoint has to be “webHttpBinding”; otherwise we get “Cannot process the message because the content type application\json was not the expected…” error.
    • webHttpBinding is the REST-style binding, where you can hit a service URL and get back a result in either XML or JSON from the service.
    webHttp Binding

    webHttp Binding

    • Add a “EndPointBehavior” with “webHttp” stack element.
webHttp Behavior

webHttp Behavior

    • Below is the service configuration mentioned in my web.config file

<services>

<service name=”ProductService”>

<endpoint address=”” behaviorConfiguration=”endPtBehaviorJSon

binding=”webHttpBinding” bindingConfiguration=”bindingWebHttp”

name=”wsBindingBFS” contract=”IProductService” />

</service>

</services>

<behaviors>

<endpointBehaviors>

<behavior name=”endPtBehaviorJSon“>

<webHttp />

</behavior>

</endpointBehaviors>

</behaviors>

Jscript

  • Since we are using JQuery, refer “JQuery.1.4.1.min.js” file
  • In this example we are getting output in json format. (Observe “dataType property mentioned as “json”)
  • getProducts” is the function which communicate to service and gets “Product” collection as response in JSon format.
  • The response comes in special format (i.e., WCF Service method name+Result)  (i.e, GetProductsResult)

function getProducts() {

var serviceURL = “http://{Server Name}/ProductService.svc/GetProducts“;

$.ajax({

type: “POST”,

contentType: “application/json; charset=utf-8”,

url: serviceURL,

processData: false,

dataType: “json”,

//If the call succeeds

success:

function (response) {

retrieveProducts(response)

},

//If the call fails

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(“Error while retrieval – ” + XMLHttpRequest.responseText);

}

});

}

function retrieveProducts(response) {

// Result collection come as Response.{MethodName}+”Result”

if (response && response.GetProductsResult) {

$.each(response.GetProductsResult, function (i) {

alert(

“Product ID: ” + this.ProductId +

” Product Name: ” + this.ProductName);

});

}

}

Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: