Upgrading ASMX web services to WCF

by Ishai Hachlili 15. June 2008 09:21

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.
When I was working on the AJAX search page, WCF was not around (it was by the time I posted the series on it here). I used XSLT to transform data to JSON and arrays. It was another step I had to do on the server side but it’s worth it, JSON is smaller than XML and very easy to work with in JavaScript.
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
  • default.aspx – the service defined in the ScriptManager was changed to the svc file and the path was updated in the javascript Search method

 

WcfAjaxSearchSample.rar (883.99 kb)

Tags: , ,

AJAX | Asp.Net | WCF

blog comments powered by Disqus

About Me

Ishai Hachlili is a web and mobile application developer.

Currently working on Play The Hunt and The Next Line


Recent Tweets

Twitter October 23, 05:22
@BenThePCGuy a standard where that doesn't matter is better. One more reason to get the #Lumia920, wireless charging, no need for microUSB

Twitter October 23, 05:21
@ManMadeMoon where they dance around the issues and don't really talk about them

Twitter October 23, 05:20
@BenThePCGuy are you a @wpdev ?

Twitter October 23, 04:17
@JonahLupton But if it's black it's usually better

Twitter October 23, 02:58
@jongalloway next time ask your 5 year old how to spell

@EShy