web-api
  1. web-api-choosing-between-ihttpactionresult-and-httpresponsemessage

Choosing Between IHttpActionResult and HttpResponseMessage - (Web API ActionResult vs HttpResponseMessage)

When building Web APIs in ASP.NET, you have two options for returning responses: using IHttpActionResult or HttpResponseMessage. While both options can achieve the same result, there are some differences between them in terms of syntax, performance, and flexibility.

Syntax

To return a response using IHttpActionResult, you simply need to return a class that implements the interface, such as OkResult or BadRequestResult. Here is an example:

public IHttpActionResult Get(int id)
{
    var entity = dbContext.Entities.SingleOrDefault(e => e.Id == id);

    if (entity == null) return NotFound();

    return Ok(entity);
}

On the other hand, returning HttpResponseMessage requires more verbose syntax and manual construction of the response message object. Here is an example:

public HttpResponseMessage Get(int id)
{
    var entity = dbContext.Entities.SingleOrDefault(e => e.Id == id);

    if (entity == null) return Request.CreateResponse(HttpStatusCode.NotFound);

    return Request.CreateResponse(HttpStatusCode.OK, entity);
}

Example

Here is a more complete example of using both IHttpActionResult and HttpResponseMessage in an ASP.NET Web API:

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    [Route("{id}")]
    public IHttpActionResult Get(int id)
    {
        var product = productService.GetProduct(id);

        if (product == null)
            return NotFound();

        return Ok(product);
    }

    [Route("{id}")]
    public HttpResponseMessage Delete(int id)
    {
        var result = productService.DeleteProduct(id);

        if (!result.Successful)
            return Request.CreateResponse(HttpStatusCode.NotFound);

        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

Output

The output of both methods would be the same HTTP response, but the syntax and construction of that response would differ.

Explanation

The IHttpActionResult interface provides a simpler and more readable syntax for returning responses, while the HttpResponseMessage approach offers more fine-grained control over the response construction (headers, status codes, etc.). However, that extra control comes at the cost of more complex syntax. Furthermore, IHttpActionResult also has the benefit of being unit-testable, while HttpResponseMessage is not.

Use

It's primarily

Published on: