Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / XML

How to create a JSON WCF RESTful Service in 60 seconds

Rate me:
Please Sign up or sign in to vote.
4.85/5 (56 votes)
10 Mar 2011CPOL2 min read 594.4K   84   51
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
<?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:

C#
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:

C#
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)


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

Comments and Discussions

 
QuestionJavaScript Client for this Service Pin
Jim Rolph10-Aug-18 13:43
Jim Rolph10-Aug-18 13:43 
QuestionWorks on localhost but not on server Pin
Member 117349026-Oct-17 2:30
Member 117349026-Oct-17 2:30 
QuestionEasiest example that actually work! Pin
JoseLozano13-Apr-17 2:43
JoseLozano13-Apr-17 2:43 
QuestionYou da man Mr. Steven Hollidge Pin
Eiinewton17-Jun-16 6:58
Eiinewton17-Jun-16 6:58 
GeneralMy vote of 4 Pin
Fawad Raza20-Dec-15 23:06
Fawad Raza20-Dec-15 23:06 
Questionyou didnt explain the webconfig setting,however it doesnt work Pin
varun15019-Oct-15 17:30
varun15019-Oct-15 17:30 
Questionunable to generate a meta address Pin
Member 1179016024-Jun-15 9:53
Member 1179016024-Jun-15 9:53 
AnswerThanks Pin
Member 1168461022-Jun-15 22:32
Member 1168461022-Jun-15 22:32 
QuestionThanks Pin
Member 1161579617-Apr-15 3:43
Member 1161579617-Apr-15 3:43 
QuestionIt doesn't work for me Pin
Nadeesha Gayan Premadasa18-Feb-15 17:57
Nadeesha Gayan Premadasa18-Feb-15 17:57 
GeneralVote of 5 in response of "Vote of 1's" Pin
Kobus du Toit9-Feb-15 19:36
Kobus du Toit9-Feb-15 19:36 
GeneralMy vote of 5 Pin
karenpayne9-Sep-14 6:26
karenpayne9-Sep-14 6:26 
QuestionUnable to connect Pin
Riya200327-Mar-14 4:55
Riya200327-Mar-14 4:55 
Questionconsultation Pin
jhonatan02995-Dec-13 11:39
jhonatan02995-Dec-13 11:39 
AnswerRe: consultation Pin
sgissinger13-Nov-14 1:04
sgissinger13-Nov-14 1:04 
GeneralMy vote of 1 Pin
baytu1-Oct-13 23:07
baytu1-Oct-13 23:07 
GeneralRe: My vote of 1 Pin
sgissinger13-Nov-14 1:06
sgissinger13-Nov-14 1:06 
GeneralMy vote of 1 Pin
baytu1-Oct-13 23:06
baytu1-Oct-13 23:06 
GeneralMy vote of 5 Pin
cstogian31-Aug-13 1:17
cstogian31-Aug-13 1:17 
QuestionHow about POST a json string to the request? Pin
franklinraj11-Jul-13 5:30
franklinraj11-Jul-13 5:30 
SuggestionAn alternative walkthough.. Pin
Michael Gledhill5-Feb-13 7:06
Michael Gledhill5-Feb-13 7:06 
GeneralRe: An alternative walkthough.. Pin
karenpayne3-Mar-14 8:31
karenpayne3-Mar-14 8:31 
GeneralRe: An alternative walkthough.. Pin
Fawad Raza20-Dec-15 23:03
Fawad Raza20-Dec-15 23:03 
GeneralMy vote of 5 Pin
Joel Ivory Johnson30-Jan-13 4:56
professionalJoel Ivory Johnson30-Jan-13 4:56 
QuestionPublish it on IIS 7 Pin
m.gaber26-Dec-12 3:26
m.gaber26-Dec-12 3:26 

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

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