Making WCF (Windows Communication Foundation) Services Simpler and More Efficient

This week, I was teaching Learning Tree course 2620: .NET 4 Programming for Existing .NET Developers. This course covers many of .NET’s new features and how they can be used to simplify development. In one chapter we talk about taking advantage of some WCF features

WCF Configure-less Services

There are a number of things that make WCF complex. One is its configuration, which is done in XML. You can get rid of the WCF configuration. In Visual Studio, right-click on the service and select View Markup.  Then add the code that is highlighted in the screenshot below:

If that’s hard to read, you’re just adding the following attribute to the markup in the service’s .svc file.



Now, the service configuration can be deleted from the Web.config file. That factory class already knows how to configure the service.

Making WCF Services Easier to Call

By default, WCF services use SOAP version 1.2 for sending messages between clients and services. The “S” in SOAP stands for “Simple”, but SOAP is far from a simple protocol. It’s so complex, you need to create what’s called a proxy to send and receive the messages. It would be easier to just make the requests via a plain old http get. To do that, add the [WebGet] attribute to the service methods as shown below. 

Calling the service above is now as simple as making the following http request from your favorite language.

Making WCF Services Easier to Consume

A WCF service returns its results in XML format. The XML for a collection of pets might look as follows:

XML is both an inefficient way of transporting data, and can be difficult to parse. An easier and more efficient format is JSON. This is especially true if the client is using JavaScript, as JSON is JavaScript.

Scroll up a little and take another look at the [WebGet] attribute. Notice, the ResponseFormat property is set to return JSON. Below is what the JSON data looks like:

Deserializing JSON in .NET

JSON is easy if you’re using JavaScript, but what about if you’re using a .NET language like C#? It turns out that consuming the JSON is no problem thanks to the DataContractJsonSerializer class in .NET.  Check out the code below.  Just take the response and convert it back into Pet objects at the client. 

To learn more about .NET, come to one of the many courses in Learning Tree’s .NET curriculum.

Doug Rehnstrom

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.