Click here to Skip to main content
11,491,459 members (73,172 online)
Click here to Skip to main content

How to create a JSON WCF RESTful Service in 60 seconds

, 10 Mar 2011 CPOL 241.9K 7.2K 60
Rate this:
Please Sign up or sign in to vote.
How to expose JSON data over a RESTful interface.

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)

Share

About the Author

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

Comments and Discussions

 
QuestionThanks Pin
Member 1161579617-Apr-15 4:43
memberMember 1161579617-Apr-15 4:43 
QuestionIt doesn't work for me Pin
Nadeesha Gayan Premadasa18-Feb-15 18:57
memberNadeesha Gayan Premadasa18-Feb-15 18:57 
GeneralVote of 5 in response of "Vote of 1's" Pin
Kobus du Toit9-Feb-15 20:36
memberKobus du Toit9-Feb-15 20:36 
GeneralMy vote of 5 Pin
kevininstructor9-Sep-14 7:26
memberkevininstructor9-Sep-14 7:26 
QuestionUnable to connect Pin
Riya200327-Mar-14 5:55
memberRiya200327-Mar-14 5:55 
Questionconsultation Pin
jhonatan02995-Dec-13 12:39
memberjhonatan02995-Dec-13 12:39 
AnswerRe: consultation Pin
sgissinger13-Nov-14 2:04
membersgissinger13-Nov-14 2:04 
GeneralMy vote of 1 Pin
baytu2-Oct-13 0:07
memberbaytu2-Oct-13 0:07 
GeneralRe: My vote of 1 Pin
sgissinger13-Nov-14 2:06
membersgissinger13-Nov-14 2:06 
GeneralMy vote of 1 Pin
baytu2-Oct-13 0:06
memberbaytu2-Oct-13 0:06 
GeneralMy vote of 5 Pin
cstogian31-Aug-13 2:17
membercstogian31-Aug-13 2:17 
QuestionHow about POST a json string to the request? Pin
franklinraj11-Jul-13 6:30
memberfranklinraj11-Jul-13 6:30 
SuggestionAn alternative walkthough.. Pin
MikeGledhill5-Feb-13 8:06
memberMikeGledhill5-Feb-13 8:06 
GeneralRe: An alternative walkthough.. Pin
kevininstructor3-Mar-14 9:31
memberkevininstructor3-Mar-14 9:31 
GeneralMy vote of 5 Pin
Joel Ivory Johnson30-Jan-13 5:56
memberJoel Ivory Johnson30-Jan-13 5:56 
QuestionPublish it on IIS 7 Pin
m.gaber26-Dec-12 4:26
memberm.gaber26-Dec-12 4:26 
GeneralMy vote of 4 Pin
wesley_jr4018-Dec-12 7:04
memberwesley_jr4018-Dec-12 7:04 
QuestionRemote Restful services are not working Pin
bindugadu7-Nov-12 4:18
memberbindugadu7-Nov-12 4:18 
Questionmy vote of 3 Pin
Wen Hao4-Nov-12 22:48
memberWen Hao4-Nov-12 22:48 
GeneralMy vote of 1 Pin
Dmitry Gonchar30-Oct-12 5:47
memberDmitry Gonchar30-Oct-12 5:47 
Bug[My vote of 2] Great detail; too bad it doesn't work Pin
jltik12-Oct-12 11:20
memberjltik12-Oct-12 11: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 work Pin
Member 46643481-Oct-12 14:09
memberMember 46643481-Oct-12 14:09 
QuestionPerfekt Work! Pin
Member 20393547-Aug-12 1:46
memberMember 20393547-Aug-12 1:46 
QuestionThis article is of zero use. Pin
mahakam1-Aug-12 7:06
membermahakam1-Aug-12 7:06 
AnswerRe: This article is of zero use. Pin
jim lahey21-Aug-12 5:04
memberjim lahey21-Aug-12 5:04 
AnswerRe: This article is of zero use. Pin
Derek Viljoen13-Sep-12 6:54
memberDerek Viljoen13-Sep-12 6:54 
GeneralMy vote of 5 Pin
aishar19-May-12 22:41
memberaishar19-May-12 22:41 
GeneralMy vote of 5 Pin
Rob Philpott17-Apr-12 2:16
memberRob Philpott17-Apr-12 2:16 
GeneralMy vote of 1 Pin
Member 313671823-Feb-12 19:48
memberMember 313671823-Feb-12 19:48 
QuestionCould not get this demo to work outside the debugger Pin
Member 848605113-Dec-11 11:13
memberMember 848605113-Dec-11 11:13 
AnswerRe: Could not get this demo to work outside the debugger Pin
GeertSchneider19-Jan-12 0:42
memberGeertSchneider19-Jan-12 0:42 
QuestionWCF service host cannot find any service metadata Pin
Peter Sedman15-Nov-11 3:49
memberPeter Sedman15-Nov-11 3:49 
AnswerRe: WCF service host cannot find any service metadata Pin
Member 1006555420-May-13 9:12
memberMember 1006555420-May-13 9:12 
QuestionHow do I find my port number Pin
MikeClarke3-Nov-11 13:05
memberMikeClarke3-Nov-11 13:05 
Questionservice1 has multiple contracts Pin
geordiej30-Jun-11 4:31
membergeordiej30-Jun-11 4:31 
GeneralNot working for me Pin
mrchief_200010-May-11 12:21
membermrchief_200010-May-11 12:21 
GeneralThis is not working for me Pin
Member 776037623-Mar-11 5:58
memberMember 776037623-Mar-11 5:58 
JokeObvious Problem In The Sample Pin
markgmarkg12-Mar-11 7:52
membermarkgmarkg12-Mar-11 7:52 
GeneralRe: Obvious Problem In The Sample Pin
StevenHollidge13-Mar-11 0:10
memberStevenHollidge13-Mar-11 0:10 
GeneralMy vote of 3 Pin
maq_rohit10-Mar-11 5:59
membermaq_rohit10-Mar-11 5:59 
GeneralRe: My vote of 3 Pin
nano2k15-May-12 5:05
membernano2k15-May-12 5:05 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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