In my previous post I wrote about first steps in creating Rest-full API by using ApiController. Now it`s time to make next step and go a little bit dipper inside web services created in MVC. In this post I want to describe two very important aspect:
- creating a real life scenario for web service implementation of POCO entity
- extend presented scenario and make it asynchronous
To complete this tutorial one more class is needed. This class is a simple fake of some database which is wrapper around a very few collections and allow all CRUD operation. Moreover the implementation of this fake database uses a singleton design pattern to prevent creating instance of it each time and maintain state between web service calls.
The real life scenario that we want to implement is a simple web service which expose all CRUD operation and of course it`s base on REST. In the following class each API functions return the same type HttpResponseMessage which represent a standard HTTP response. This type contains two important properties: StatusCode - which represent a HTTP response status code and Content - which store body of the response if any. The the easiest to produce a HttpResponseMessage is calling one of many build-in functions which are responsible for creating a fully qualified response based on several input parameter:
- Request.CreateResponse - the simplest method for returning any type of response with or without content
- Request.CreateResponse<T> - create a success response with content of T type
- Request.CreateErrorResponse - create a error response and requires to specify HTTP code status and exception
Now our service is ready to use and we run it and we can call each GET, POST, PUT and DELETE function by using any of HTTP Client.
|Picture 1. Calling GET and POST API from test HTTP Client.|