My two cents on using the IHttpActionResult interface in WebAPI

Choose IHttpActionResult as the response return type for your WebAPI controller methods to make your action methods easier to read, test and maintain and also abstract the way the HTTP responses are actually constructed

ihttpactionresult
IDG

Microsoft's WebAPI has for quite some time been the framework of choice for building RESTful services that can work over HTTP. The IHttpActionResult interface has been introduced with WebAPI version 2 and provides a different way to send back responses from your WebAPI controller methods, and it leverages async and await by default.

Essentially, IHttpActionResult is a factory for HttpResponsemessage. The IHttpActionResult interface is contained in the System.Web.Http namespace and creates an instance of HttpResponseMessage asynchronously. The IHttpActionResult comprises a collection of custom in-built responses that include: Ok, BadRequest, Exception, Conflict, Redirect, NotFound, and Unauthorized.

The IHttpActionResult interface contains just one method. Here's how this interface looks:

namespace System.Web.Http

{

    public interface IHttpActionResult

    {

        Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);

    }

}

You can return a custom response using any of the helper methods of the ApiController class listed below.

Ok

NotFound

Exception

Unauthorized

BadRequest

Conflict

Redirect

InvalidModelState

Returning response from WebAPI controller methods

In this section we will explore how we can leverage IHttpActionResult to send back responses from the controller methods.

Now, consider the following WebApi controller:

public class DefaultController : ApiController

    {

        private readonly DemoRepository repository = new DemoRepository();

        public HttpResponseMessage Get(int id)

        {

            var result = repository.GetData(id);

            if (result != null)

                return Request.CreateResponse(HttpStatusCode.OK, result);

            return Request.CreateResponse(HttpStatusCode.NotFound);

        }

    }

Note that the appropriate status code is returned in each case, i.e., if data is available, HttpStatusCode.OK is returned while HttpStatusCode.NotFound is returned if data is not available.

Let’s now see how the same controller method can be changed to return the response as IHttpActionResult. Here’s the updated code of the controller method for your reference. Note how HttpResponseMessage has been replaced with IHttpActionResult.

public IHttpActionResult Get(int id)

        {

            var result = repository.GetData(id);

            if (result == null)

                return NotFound();

            return Ok(result);

        }

Refer to the Get method given above. The code is much simple and lean and it abstracts the way the Http message is actually constructed in the controller. And, here’s another example.

Refer to the following code snippet that returns HttpResponseMessage to report success or failure.

public HttpResponseMessage Delete(int id)

        {

            var status = repository.Delete(id);

            if (status)

               return new HttpResponseMessage(HttpStatusCode.OK);

            return new HttpResponseMessage(HttpStatusCode.NotFound);

        }

Now see how the same action method can be refactored using IHttpActionResult to make the code much more lean and simple.

public IHttpActionResult Delete(int id)

        {

            var status = repository.Delete(id);

            if (status)

              return Ok();

            return NotFound();

        }

Which one should I use and why?

So, should we use IHttpActionResult over HttpResponseMessage in our WebAPI controllers when sending back the responses? Here's my answer to this question. I would always prefer IHttpActionResult over HttpResponseMessage as in doing so, unit testing of the controllers would become simplified. You can move the common logic for creating Http responses to other classes and make your controller methods lean and simple. In essence, the low level details of creating the Http responses would be encapsulated.

On a different note, it is worth mentioning that in using IHttpActionResult, you can adhere to the Single Responsibility Principle as well as your action methods can focus on handling the Http requests rather than construct the Http response messages. There is another point worth mentioning. You can take advantage of IHttpActionResult to provide support for HTML with Razor. All you need to do is create a custom action result that can parse Razor views. Creating a custom action result is simple. You would just need to extend the IHttpActionResult interface and then implement your own version of the ExecuteAsync method.

Copyright © 2017 IDG Communications, Inc.