In this post I will document a simple application to call a WCF service using JQuery. To make this happens I used the following definition in the .svc markup
<%@ ServiceHost Language="C#" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" Service="Guava.Server.Web.Services.GuavaService" %>
In the above code I used WebScriptServiceHostFactory, in this way it enables some configurations to allow the service to be called by AJAX. Alternative implementation is setting the configuration to enable web script behavior.
The following code defines my service
[ServiceContract(Namespace = "http://guava", Name = "GuavaService")] public interface IGuavaService { [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] void Execute(string name); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] string Version(string name); } [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class GuavaService : IGuavaService { public void Execute(string name) { } public string Version(string name) { return "1.0"; } }
The AspNetCompatibilityRequirements attributes ensures compatibility with AJAX calls.
To allow GET methods define the method with the WebGet attribute.
To allow POST methos define the method with the following attribute
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
From the above code the BodyStyle must be defines as WrappedRequest
The following code shows my JQuery call
function OnError(jqXHR, textStatus, errorThrown) {
if (jqXHR.textStatus === 'error') {
}
}
function OnVersionCompleted(data, textStatus, jqXHR) {
alert(data.d);
}
function OnVersion() {
$.getJSON('Services/GuavaService.svc/Version?name=John', {}, OnVersionCompleted);
}
function OnExecuteCompleted(data, textStatus, jqXHR) {
alert('OnExecuteCompleted');
}
function OnExecute() {
$.ajax({
url: 'Services/GuavaService.svc/Execute',
type: 'POST',
data: '{ "name" : "John" }',
dataType: 'json',
contentType: 'application/json',
success: OnExecuteCompleted,
error: OnError
});
}
For the POST method it is important to express your data as Json string format.