Returning IHttpActionResult
We mentioned above that the HttpResponseMessage object is a standard object to return from Web API actions. Web Api 2 introduces another type of object that you can return from an API action: IHttpActionResult. It is similar to ActionResult in standard ASP.NET MVC. In MVC you can return JsonResult, ContentResult and View objects. With this new return type in the Web API you can return similar objects that are specific to HTTP traffic:
- OkResult
- NotFoundResult
- ExceptionResult
- UnauthorizedResult
- BadRequestResult
- ConflictResult
- RedirectResult
- InvalidModelStateResult
…and many more. You can even create your custom Result object by deriving from an existing concrete object that implements the IHttpActionResult interface or by implementing the interface directly. Let’s see how we can transform our current code.
Let change
To
The code will not compile any more of course as the HttpResponseMessage object doesn’t implement this interface. It’s incredibly easy to send a NotFount and Ok response. Change the body of Get(id) to the following:
We can change GetAlbums to the following: