Click here to Skip to main content
Click here to Skip to main content

How to create a JSON WCF RESTful Service in 60 seconds

By , 10 Mar 2011
 

WCF makes it very easy to expose JSON data over a RESTful interface, as long as you are aware of a couple of “gotchas” in advance.

This article will explain those to you, so you can focus on your business logic rather than configuration of your WCF services.

We start this example by creating a WCF Service Library project:

new-project

Next we need to add a reference to the System.ServiceModel.Web framework.  Right click on your project file and select Add Reference…

add-reference

As this framework is not part of the .Net Framework 4 Client Profile, Visual Studio kindly informs us that it will update our target Framework to the full version of .Net Framework 4.  Click Yes to accept this change:

target-change

We are now ready to update our code.

Copy and paste the following code into the App.Config file:

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
	<services>
	  <service name="WcfJsonRestService.Service1">
		<endpoint address="http://localhost:8732/service1" 
				  binding="webHttpBinding" 
				  contract="WcfJsonRestService.IService1"/>
	  </service>
	</services>
	<behaviors>
	  <endpointBehaviors>
		<behavior>
		  <webHttp />
		</behavior>
	  </endpointBehaviors>
	</behaviors>
  </system.serviceModel>
  <startup>
	<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

Notice the binding is set to webHttpBinding as opposed to the normal project template default of wsHttpBinding. 

The other important change is the addition of an endpointBehavior for WebHttp.

These two changes are required to enable JSON over REST for WCF.

Copy and paste the following code into the IService1 file:

using System.ServiceModel;

namespace WcfJsonRestService
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Person GetData(string id);
    }
}

Notice we are accepting an “In” parameter for id of datatype string.  For this example we are returning a custom type of Person.

Copy and paste the following code into the Service1.cs file:

using System;
using System.ServiceModel.Web;

namespace WcfJsonRestService
{
    public class Service1 : IService1
    {
        [WebInvoke(Method = "GET", 
                    ResponseFormat = WebMessageFormat.Json, 
                    UriTemplate = "data/{id}")]
        public Person GetData(string id)
        {
            // lookup person with the requested id 
            return new Person()
                       {
                           Id = Convert.ToInt32(id), 
                           Name = "Leo Messi"
                       };
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

The key elements here are the attributes applied to the method.  We are enabling the method to be called over HTTP GET, returning the data in Json format and setting the Uri template to ensure we are using a RESTful interface.

To test your brand new service we will pass in the id value of 10 simply by opening your favourite browser and pasting in the following URL: 

http://localhost:8732/Service1/data/10

json-browser

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

StevenHollidge
Software Developer (Senior)
United Kingdom United Kingdom
Member
Developer of .Net Enterprise solutions in the City of London

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionAn alternative walkthough..memberMikeGledhill5 Feb '13 - 7:06 
Here's an alternative walkthrough, which shows how to create a WCF Web Service, which uses JSON, and then extends it to return data from SQL Server.
 
http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm
 
Awesome!
GeneralMy vote of 5memberJoel Ivory Johnson30 Jan '13 - 4:56 
Short yet useful. Of high utility.
QuestionPublish it on IIS 7memberm.gaber26 Dec '12 - 3:26 
Good Job Steven .... the web service can run on vs iis
but i want to publish it on IIS7 can you till me how to do that and what will happen with the address in the app.config ?
GeneralMy vote of 4memberwesley_jr4018 Dec '12 - 6:04 
Great doc!!!
QuestionRemote Restful services are not workingmemberbindugadu7 Nov '12 - 3:18 
Hello Steven,
 
This artical really help me for creating WCF RESTful service,
but when i host this service in the IIS. It is not working(Throwing Page not found error.)
 
Could you please help me on this issue.
 
Thanks for any kind of help.
 

Regards,
Pavan
Questionmy vote of 3memberWen Hao4 Nov '12 - 21:48 
This code will only work in IE if you access the wcf service using jquery.
You have to enable your crossDomainScriptEnabled to true.
GeneralMy vote of 1memberDmitry Gonchar30 Oct '12 - 4:47 
does not work
Bug[My vote of 2] Great detail; too bad it doesn't workmemberjltik12 Oct '12 - 10:20 
It seems very simple, but something basic must be missing. Get 404 error using your downloaded code, same port and everything.
QuestionSorry it dose not workmemberMember 46643481 Oct '12 - 13:09 
Yes the Base from where you are starting is good you want like to explain how to implement a Json service.
But nobody can use your information really without more explanation about how to get the project work.
 
Thumbs Down | :thumbsdown: Thumbs Down | :thumbsdown: Thumbs Down | :thumbsdown: Thumbs Down | :thumbsdown:
Java | [Coffee]
QuestionPerfekt Work!memberMember 20393547 Aug '12 - 0:46 
on the point the thing i need!
thank you very very mutch!!!!!
Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 10 Mar 2011
Article Copyright 2011 by StevenHollidge
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid