Introduction:
This article explains how to communicate with Windows Communication Foundation (WCF) services from Jquery.
1. Change your WCF service attribute.
2. Adding attributes to the Operation Contract.
3. Add end point in WCF web.config file.
4. Consume the service from Jquery.
Step 1: Change your WCF Service Attribute
To make your WCF service to work like normal ASMX service, service need to be changed to indicate whether that service can be run in ASP.Net Compatibility mode.
Sample code mentioned below sets the ASP.Net Compatibility mode
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetMyName(string firstName, string lastName)
{
return firstName + lastName;
}
}
Step 2: Adding attributes to your Operation Contract
"WebInvoke" attribute needs to be added to all your “OperationContract” to get/return the values in JSON format. Your “OperationContract” should be modified as mentioned below.
[ServiceContract]
public interface IService1
{
// TODO: Add your service operations here
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetMyName(string firstName,string lastName);
}
Step 3: Add end point in WCF web.config
To make your service with HTTP protocol request you need to specify the “webHttpBinding” in your web.config file. Same is mentioned below.
<system.serviceModel>
<services>
<service name="MyWCFService.Service1" behaviorConfiguration="MyWCFService.Service1Behavior">
<endpoint address="" binding="webHttpBinding" contract="MyWCFService.IService1" behaviorConfiguration="EndPointBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWCFService.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndPointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Step 4: Consume the Service through Jquery
To consume the WCF service, Jquery has to make a call by using Jquery.ajax() method. Same is shown below.
<script type="text/javascript">
function CallMyService() {
$.support.cors = true;
var param = '{"firstName": "FirstName","lastName": "LastName"}';
$.ajax({
type: "POST",
url: "http://localhost:44017/Service1.svc/GetMyName",
data: param,
contentType: "application/json",
success: ServiceSucceeded,
error: ServiceFailed
});
}
// ---- If Error -------------------
function ServiceFailed(result) {
Log('Failed: ' + result.status + ' ' + result.statusText);
}
// ---- If Success -------------------
function ServiceSucceeded(result) {
var resultObject = result.GetMyNameResult;
Log("Success: " + resultObject);
}
function Log(msg) {
// Log your Message.
alert(msg);
}
$(document).ready(
function () {
CallMyService();
}
);
</script>
Note:
1. $.support.cors = true; It should be used before calling jquery.ajax() method to enable the cross browser functionality through Jquery.
2. “ServiceSucceeded” method checks the response by getting result.GetMyNameResult object. It is nothing but MyWCFServiceName + Result. “Result” should suffix with your “Webservice” name to get the response. |