There is a lot of information on the web on using WCF for JSON, but I figured I’ll writing something short on the way I use it.
When I decided to try WCF, the first thing I noticed was how simple it was to upgrade. All you need to do is add a new WCF Service to the web project, copy the code from the ASMX service, change the [ScriptService] to [ServiceCntract] and the [WebMethod] tags to [OperationContract] and add some definitions in the web.config file.
You’re supposed to use a separate Interface to define the service contract, but it’s not a must and you can add the tags to the actual class with the implementation.
The second thing I noticed is that I can get JSON by changing some configuration settings.
With WCF I just change a small definition and I get the results in JSON, no need for the XSLT transformation.
Another thing we get with WCF is Data Contracts. The way I’m using it in this sample, it’s pretty much the same as using the .Net AJAX GenerateScriptType.
All I had to do is add a [DataContract] tag to the class and [DataMember] tags to each property.
I think it’s better to define this on the exposed class itself instead of adding some register definition in a web service.
The attached project is the same search page sample with the WCF service. The changes to look for are:
- The new DataService.svc file
- The Entities.QueryParameters classes now have the DataContract tags
- web.config has the new serviceModel section at the end, that defines the service as an HTTP JSON enabled service
WcfAjaxSearchSample.rar (883.99 kb)