Consuming cross-domain WCF REST services with Jquery using JSON
Download
Step 1:
Create a solution with three projects.
1. ServiceLibrary (WCF Service Library)
2. Host (WCF Service Application)
3. Client (ASP.NET Empty Web Application)
Step 2:
Modify the app.config, IService.cs and Service.cs as follows in ServiceLibrary application.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
<authentication mode="None"/>
</system.web>
<system.serviceModel>
<services>
<service name="ServiceLibrary.Service1" behaviorConfiguration="DefaultBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/service"/>
</baseAddresses>
</host>
<endpoint address="basic" binding="basicHttpBinding" contract="ServiceLibrary.IService1"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
**********************************************************************
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace ServiceLibrary
{
[ServiceContract]
public interface IService1
{
[OperationContract(Name="GetSample")]
[WebInvoke(Method="GET", UriTemplate = "GetSample?value={value}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetData(string value);
[OperationContract(Name="PostSample")]
[WebInvoke(Method = "POST", UriTemplate = "PostSample/compositeType", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
CompositeType GetDataUsingDataContract(CompositeType compositeType);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
**********************************************************************
using System;
using System.ServiceModel.Activation;
namespace ServiceLibrary
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(String value)
{
return String.Format(value);
}
public CompositeType GetDataUsingDataContract(CompositeType compositeType)
{
return compositeType;
}
}
}
**********************************************************************
Step 3:
Do following in Host application.
1. Delete IService1.cs
2. Rename Service1.svc to Service.svc
3. Open Service.svc and update it as follows
<%@ ServiceHost Language="C#" Debug="true" Service="ServiceLibrary.Service1" CodeBehind="ServiceLibrary.Service1.cs" %>
4. Select Host application press mouse right click select Add Reference.. navigate to project and select ServiceLibrary and press ok.
5. Select Host application press mouse right click select Add New Item..add Global.asax file in project and update it as follows
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
HttpContext.Current.Response.End();
}
}
6. Open Web.config and update it as follows
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="None"/>
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="DefaultBehavior" name="ServiceLibrary.Service1">
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="webHttpBindingWithJsonP" contract="ServiceLibrary.IService1"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
crossDomainScriptAccessEnabled="true" >
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
6. Open Web.config and update it as follows
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="None"/>
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="DefaultBehavior" name="ServiceLibrary.Service1">
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="webHttpBindingWithJsonP" contract="ServiceLibrary.IService1"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
crossDomainScriptAccessEnabled="true" >
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
7. Create a folder in Win Drive:\inetpub\wwwroot\RestService
8. Press (Win key) + R type inetmgr press enter.
9. Navigate to RestService press mouse right clickselect Convert To Application.
10. Select Host application press mouse right click select publish..
**********************************************************************
Step 4:
Do following in Client application.
1. Download the latest jquery library from http://jquery.com/download/
2. Select Client application press mouse right click select Add New Item..add a Web Form and update it as follows.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
var json = {BoolValue: true,StringValue: "Hellow World !"};
json = JSON.stringify(json);
$(document).ready(function () {
document.writeln(json + "<br/>");
$.ajax({
cache:false,
url: 'http://localhost/RestService/Service.svc/json/GetSample?value=abcd',
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (response) {
alert("GET " + response);
},
error: function (xhr) {
document.writeln("error");
}
});
$.ajax({
cache: false,
url: 'http://localhost/RestService/Service.svc/json/PostSample/compositeType',
data: json,
processData: true,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (response) {
alert("BoolValue: " + response.BoolValue + " StringValue: " + response.StringValue);
},
error: function (xhr) {
document.writeln("error");
}
});
});
</script>
**********************************************************************
Step 5:
Select Client application and set it as a Start Up project and run the application if every thing goes well you will get following response.
- Request URL:http://localhost/RestService/Service.svc/json/PostSample/compositeType
- Request Method:POST
- Status Code:200 OK
And
- Request URL:http://localhost/RestService/Service.svc/json/GetSample?value=Hello%20World%20!&_=1367430400381
- Request Method:GET
- Status Code:200 OK
No comments:
Post a Comment