Exposing a JSON Restful service with WCF is very easy. Lets take a look how we can do that.

I am assuming that a WCF library or other WCF project was created and the ServiceModel reference is included. This was tested with VS2010 and C# 4.0.

Service Interface

So, lets create the Service interface:

 

WebInvoke: specifies that the method will obey POST-requests

WebGet: specifies that the method will obey GET-requests

ResponseFormat: specifies the how the data should be formatted. In our case, it is Json. This returns a clean and simple JSON notation.

UriTemplate: specifies how this method can be called. In the above example it is /jsonGet/{id}, this means, that our method can be called like this: http://localhost:62464/RestService.svc/jsonGet/1. See that the method is called within the svc.

The GetStudent method returns then something like this:

 

Service Implementation

Now, lets implement our servicesinterface.

This is just an example implementation to show that everything is working fine.

Data Model

For that example, we also need a data model student

 

Web.config

And finally, we also need to configure our JSON Restful services

 

Lets see how we configure the Service. We will need a specifig behaviorConfiguration called json and the binding must be webHttpBinding.

Then, under the behaviours and endpointbehaviours we will define our json behavior. There we need the webHttp element. 

I needed to disable the aspNetCompatibility under the serviceHostingEnvironment to make it work. 

 

So thats it, our WCF services are now returning Json data. 

Download here the DemoWcfJson Project.

 

 

 

 

 

 

 

Expose a JSON Restful service with WCF
Tagged on:         

Leave a Reply

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: