Web API #5 - IHttpActionResult
Look at this CreateCustomer action, here we are simply returning a CustomerDto.
which would eventually result in response like this -
So, here the status code of this response is 200 or OK and in the body we have the customer object serialized as JSON.
By the RESTful convention, when we create a resource, this status code should be 201 or Created. So, we need more control over to the response return from our action, and to make this happen instead of returning customerDto, we need to return IHttpActionResult, this interface is similar to ActionResult we have in MVC framework. It implemented by few different classes and here in API controller we have a bunch of helper method to create an instance of one of the classes that implement this interface. Now here if the model is not valid instead of throwing exception, we use the helper method BadRequest(). So this BadRequest() method returns a BadRequestResult which is a class that implement IHttpActionResult. At the end instead of returning customer detail we call the Created() method.
Recommended by LinkedIn
Here as part of RESTful convention, we need to return the URI of the newly created resource to the client. URI stands for Unified Resource Identifier. So, if the id of our new customer is 10, the URI to this resource is something like this - /api/customers/10.
So, we create a new URI, this class is defined in System namespace. Now in the constructor we need to get the URI of our current request. To get the URI for the request we use Request property of the controller and then RequestUri, now append "/" and the Id of the customer. Now as the second argument to the created method we need to pass the actual object that was created which will be customerDto. Now, build the code, back to the browser and let's execute this again, all right look, first of all the status is changed from 200 which was OK to 201 which is Created. This is confirming to RESTful convention. All if you look at the Headers tab you see a new key here Location and look at the address so that is the URI of the newly created customer.
This is the part of the RESTful convention. So, in Web APIs prefer to use IHttpActionResult as the return type of your action.