Friday, 30 September 2011

WcfWebApi REST JSON Services

Overview

Here is an example of using WcfWebApi to produce a RESTful JSON data service.  We have three areas to consider:

  • Our data (model) is a simple Contact class
  • Our service is exposed via IContractService interface and implemented as ContractService
  • Our data store (repository) is exposed via IContactRepository interface and implemented as ContractRepository

diagram

RESTful Interface

Data Operation HTTP Verb Has Side Effects? Idempotent? Example Uri
Read All GET No Yes http://localhost:8000/contacts
Read Single GET No Yes http://localhost:8000/contacts/1
Insert POST Yes No http://localhost:8000/contacts
Update PUT Yes Yes http://localhost:8000/contacts
Delete DELETE Yes Yes http://localhost:8000/contacts/3

HTTP Status (Return) Codes

Http Code Description Examples
200 OK Successful (read, update or delete)
201 CREATED Successful (insert)
400 BAD REQUEST Passing id as “X” when an integer is expected
404 NOT FOUND Item not found (based on id)
500 SERVER ERROR Exception thrown within service on server with the message contained within response body.

Service Interface

Service Implementation

Service Unit Tests

Service-Unit-Tests

Hosting The Service in an ASP.NET Web Application

Alternatively…. Console Hosting

The source code also contains an example of hosting within a client application:

Client Access to the REST service interface from a Console App

Output

ScreenShot163

Monitoring

HTTP

You can use Fiddler to monitor all HTTP requests and responses.  The screenshot below shows Fiddler on the left hand side picking up all requests and responses from the WCF Web API Test Client (explained within Debugging below) on the right hand side.

Fiddler-Monitoring

Debugging

Configure the Firewall (if required)

Make sure you punch a hole in your firewall before testing (or change the port from 8010 to 80 in the source code). 

On Windows 7 > Control Panel > Windows Firewall > Allow a Program or Feature through the Firewall

ScreenShot152

Fiddler

We are now ready to open Fiddler and use the Request Builder tab to enter your URI, set the HTTP verb (defaults to GET) and execute your request.  On the left hand side you’ll see the HTTP response and headers, in this case the result was 200 (OK):

Fiddler-GET-example1

Then switch to the Inspectors tab to view the response body containing our data.

Fiddler-GET-example2

For PUT and POST requests you must add the following to the request headers:

Content-Type: application/json; charset=utf-8

Fiddler-POST-exampleFiddler-PUT-example

WCF Web API Test Client

We switched this new Microsoft Tool on in the Global.asax page with “EnableTestClient = true” which automatically routes:

In our case this would be http://localhost:8010/Contacts/Test:

ScreenShot153ScreenShot156ScreenShot157ScreenShot158ScreenShot159

 

Full source code:  http://stevenhollidge.com/blog-source-code/RestDemo.zip

1 comments: