WCF Services and AJAX
WCF Services and Ajax
In this post I show a sample of a WCF 3.5 service which supports Json.
WebGetAttribute.ResponseFormat Property
The WebMessageFormat property determines the format of responses sent from a service operation. The two possibe values are Xml and Json.
The following example demonstrates how to set the ResponseFormatProperty:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
String SayHello(String name);
}
The implementation of this service is simple:
public class Service : IService
{
public String SayHello(String name)
{
return String.Format("Hello {0}", name);
}
}
Web.Config
In Web.Config the service include webHttpBinding and jasonBehavior which contain the enableWebScript element.
The enableWebScript element enables the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages. This behavior should be used in conjunction with either <webHttpBinding> or <webMessgaeEncoding> binding element.
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint
address=""
binding="webHttpBinding"
behaviorConfiguration="jsonBehavior"
contract="IService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="jsonBehavior" >
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
ClientPage.htm
The client page create an Ajax XMLHttpRequest object, construct the url to the service and prints the response.
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<h1>AJAX WCF Sample</h1>
<form name="input">
Name: <input type="text" name="name" onclick="sayHello();" />
<div id="msg"></div>
</form>
<script type="text/javascript">
function sayHello()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
var msg = "This sample only works";
msg = msg + "in browsers with AJAX support.";
alert(msg);
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var mdiv = document.getElementById("msg");
mdiv.innerHTML = (xmlHttp.responseText);
}
}
var url = "Service.svc/";
url = url + "SayHello?name=";
url = url + document.input.name.value;
xmlHttp.open("GET", url, true);
xmlHttp.send('');
}
</script>
</body>
</html>
The result
The source for this sample can be downloaded from here.