- Settings:
Page
Normal
Plain layout without fancy styles
Font
Normal
Large fonts
Very large fonts
Colour
Normal
Restful colour scheme
Light text on a dark background

Note: user account creation on this site has been disabled.

Programming, speculative fiction, science, technology
Powered by Drupal, an open source content management system
Scope
Include Children
If you select a term with children (sub-terms), do you want those child terms automatically included in the search? This requires that "Items containing" be "any."
Categories

Everything in the Events vocabulary

"Events" is used for: Convention Post, Page, Story.

People mentioned in the articles

"People" is used for: Page, Convention Post, Story.

Themes mentioned in the article

"Themes" is used for: Page, Convention Post, Story.
Skip to top of page

Creating a RESTful WCF service that returns JSON data

When I was looking for documentation or tutorials on how to create a RESTful WCF service that returns JSON-formatted data, I found lots of partial information and code examples, none of which completely worked. So when I finally figured out how to create it, I decided to write this article for those who may be in the same predicament as me.

This walk-through uses .NET 4.0, and Visual Studio 2010.

Creating the service

In Visual Studio, go to New Project, and create a project called WcfJsonRestServiceExample. Select the WCF Service Application template for it. (I tried to use WCF Service Library template, as some other tutorials suggested, and then ran into great difficulty trying to get IIS to use a proper handler for requests to this application. So I decided to use WCF Service Application instead, which didn't have this problem.)

It creates this skeleton code in Service1.svc.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfJsonRestServiceExample
{
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}

Let's delete the GetDataUsingDataContract method right away, since we don't need it. Let's also delete the declaration of that method from IService1.cs.

Creating the model

Now, let's follow the tutorial to which I forgot the link, which uses a class Person. We create the class Person -- our data model of sorts. It's very simple for now. You can extend it as you like.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WcfJsonRestService3
{
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
}

Modifying the service to return JSON objects

Let's modify GetData method in the service so it would return Person data.

In IService1.cs:


[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetData/{id}")]
Person GetData(string id);

In Service1.svc.cs:


public Person GetData(string id)
{
return new Person()
{
ID = Convert.ToInt32(id),
Name = "Foo Bar"
};
}

This service should return a JSON object that looks like this:

{"ID":3,"Name":"Foo Bar"}

Enabling RESTful endpoints and behaviors in Web.config

We will now enable the RESTful service endpoints and behaviors. Right now, your Web.config file looks probably like this. (Sorry about the

tags -- Drupal has put them in there. Also, this snippet only shows the relevant parts of Web.config file. It probably has all sorts of other lines in it too.)

We need to add the following sections to it. Under opening tag, add the element like this:

Under closing tag, add element like this:

Deploying the web service under IIS

Now we will deploy the web service under IIS.

Open the IIS Management Console. Under Sites, create a new site named WcfJsonRestServiceExample with a path c:\inetpub\wwwroot\WcfJsonRestServiceExample (or wherever your webroot directory is). Assign a port for it, if port 80 is already taken on your machine. Let's say you selected port 8005. The URL for this site will be http://localhost:8005.

Go back to Visual Studio. Select .Build->Publish WcfJsonRestServiceExample. from the menu. In the "Publish Web" dialog box that opens, leave Publish Method as "Web Deploy". Set "Service URL" to http://localhost:8005. Set "Site/application" to WcfJsonRestServiceExample. Leave everything else as is. Click "Publish".

Accessing the web service through the browser

Notice how GetData method has

UriTemplate = "GetData/{id}"

It means that we would invoke it like this:

http://localhost:8005/Service1.svc/GetData/3

where 3 is the id of your choice -- it can be any other integer, of course. And if you enter this URL in your browser, you'll get a JSON-formatted response:

{"ID":3,"Name":"Foo Bar"}

If you get the infamous static-file-handler-for-what-appears-to-be-a-script error, go to the IIS Management Console, click on Application Pools in the left sidebar, right-click on WcfJsonRestServiceExample, select Basic Settings, and in the "Edit Application Pool" dialog box set the .NET framework version to 4.*.* (whatever those numbers are).