Why should I use IHttpActionResult instead of HttpResponseMessage?
You can still use HttpResponseMessage
. That capability will not go away. I felt the same way as you and argued extensively with the team that there was no need for an additional abstraction. There were a few arguments thrown around to try and justify its existence but nothing that convinced me that it was worthwhile.
That is, until I saw this sample from Brad Wilson. If you construct IHttpActionResult
classes in a way that can be chained, you gain the ability to create a "action-level" response pipeline for generating the HttpResponseMessage
. Under the covers, this is how ActionFilters
are implemented however, the ordering of those ActionFilters
is not obvious when reading the action method which is one reason I'm not a fan of action filters.
However, by creating an IHttpActionResult
that can be explicitly chained in your action method you can compose all kinds of different behaviour to generate your response.
// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage);
You might decide not to use IHttpActionResult
because your existing code builds a HttpResponseMessage
that doesn't fit one of the canned responses. You can however adapt HttpResponseMessage
to IHttpActionResult
using the canned response of ResponseMessage
. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:
public IHttpActionResult SomeAction()
{
IHttpActionResult response;
//we want a 303 with the ability to set location
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
responseMsg.Headers.Location = new Uri("http://customLocation.blah");
response = ResponseMessage(responseMsg);
return response;
}
Note, ResponseMessage
is a method of the base class ApiController
that your controller should inherit from.
Here are several benefits of IHttpActionResult
over HttpResponseMessage
mentioned in Microsoft ASP.Net Documentation:
- Simplifies unit testing your controllers.
- Moves common logic for creating HTTP responses into separate classes.
- Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
But here are some other advantages of using IHttpActionResult
worth mentioning:
- Respecting single responsibility principle: cause action methods to have the responsibility of serving the HTTP requests and does not involve them in creating the HTTP response messages.
- Useful implementations already defined in the System.Web.Http.Results namely:
Ok
NotFound
Exception
Unauthorized
BadRequest
Conflict
Redirect
InvalidModelState
(link to full list) - Uses Async and Await by default.
- Easy to create own ActionResult just by implementing
ExecuteAsync
method. - you can use
ResponseMessageResult ResponseMessage(HttpResponseMessage response)
to convert HttpResponseMessage to IHttpActionResult.