Joydip Kanjilal
Contributor

My two cents on using the IHttpActionResult interface in WebAPI

opinion
Apr 25, 20173 mins
Software Development

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
Credit: 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author