Saturday 27 August 2016

Getting Started with ASP.NET Web API 2 (C#) Part 4

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:

  1. OkResult
  2. NotFoundResult
  3. ExceptionResult
  4. UnauthorizedResult
  5. BadRequestResult
  6. ConflictResult
  7. RedirectResult
  8. 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:

2 comments:

  1. HI Ravi,

    Gone through your blog and its really good one for the students starting their course and trying to learn ASP.net. It would be really great if you can address those which are not being covered in practical fields. Good start and all the best. I would recommend this to all my network.
    Best Regards,
    Sashi

    ReplyDelete

  2. very informative and impressive article. Thanks for sharing with us
    Linux Cloud Hosting

    ReplyDelete