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();
    }
}

8 Answers
8

Leave a Comment