[c#] Why should I use IHttpActionResult instead of HttpResponseMessage?

I have been developing with WebApi and have moved on to WebApi2 where Microsoft has introduced a new IHttpActionResult Interface that seems to recommended to be used over returning a HttpResponseMessage. I am confused on the advantages of this new Interface. It seems to mainly just provide a SLIGHTLY easier way to create a HttpResponseMessage.

I would make the argument that this is "abstraction for the sake of abstraction". Am I missing something? What is the real world advantages I get from using this new Interface besides maybe saving a line of code?

Old way (WebApi):

public HttpResponseMessage Delete(int id)
{
    var status = _Repository.DeleteCustomer(id);
    if (status)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    else
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

New Way (WebApi2):

public IHttpActionResult Delete(int id)
{
    var status = _Repository.DeleteCustomer(id);
    if (status)
    {
        //return new HttpResponseMessage(HttpStatusCode.OK);
        return Ok();
    }
    else
    {
        //throw new HttpResponseException(HttpStatusCode.NotFound);
        return NotFound();
    }
}

This question is related to c# asp.net-web-api httpresponse

The answer is


The Web API basically return 4 type of object: void, HttpResponseMessage, IHttpActionResult, and other strong types. The first version of the Web API returns HttpResponseMessage which is pretty straight forward HTTP response message.

The IHttpActionResult was introduced by WebAPI 2 which is a kind of wrap of HttpResponseMessage. It contains the ExecuteAsync() method to create an HttpResponseMessage. It simplifies unit testing of your controller.

Other return type are kind of strong typed classes serialized by the Web API using a media formatter into the response body. The drawback was you cannot directly return an error code such as a 404. All you can do is throwing an HttpResponseException error.


// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage); 

I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);

        switch ((Int32)_respContent.Code)
        { 
            case 1:
            case 6:
            case 7:
                response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
                break;
            case 2:
            case 3:
            case 4:
                response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
                break;
        } 

        return Task.FromResult(response);
    }

, where _request is the HttpRequest and _respContent is the payload.


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 is just my personal opinion and folks from web API team can probably articulate it better but here is my 2c.

First of all, I think it is not a question of one over another. You can use them both depending on what you want to do in your action method but in order to understand the real power of IHttpActionResult, you will probably need to step outside those convenient helper methods of ApiController such as Ok, NotFound, etc.

Basically, I think a class implementing IHttpActionResult as a factory of HttpResponseMessage. With that mind set, it now becomes an object that need to be returned and a factory that produces it. In general programming sense, you can create the object yourself in certain cases and in certain cases, you need a factory to do that. Same here.

If you want to return a response which needs to be constructed through a complex logic, say lots of response headers, etc, you can abstract all those logic into an action result class implementing IHttpActionResult and use it in multiple action methods to return response.

Another advantage of using IHttpActionResult as return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.

Of course, as noted by Darrel, you can chain action results and create a powerful micro-pipeline similar to message handlers themselves in the API pipeline. This you will need depending on the complexity of your action method.

Long story short - it is not IHttpActionResult versus HttpResponseMessage. Basically, it is how you want to create the response. Do it yourself or through a factory.


We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

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.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Examples related to httpresponse

Return content with IHttpActionResult for non-OK response Why should I use IHttpActionResult instead of HttpResponseMessage? download csv file from web api in angular js Proper way to return JSON using node or Express Writing MemoryStream to Response Object Returning http status code from Web Api controller Difference between Pragma and Cache-Control headers? How to Use Content-disposition for force a file to download to the hard drive? Return HTTP status code 201 in flask How to get HTTP Response Code using Selenium WebDriver