Last Updated: September 30, 2021
·
21.91K
· blaiseliu

From HttpResponseMessage to IHttpActionResult

Coming from the first version of WebAPI, we are all familiar with ApiController actions that returns a HttpResponseMessage:

public HttpResponseMessage Get(int id)
{
    var doc = _documentations[id];
    if (doc==null)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Documentation Not Found");
    }
    return Request.CreateResponse(doc);
}

Now, WebAPI provides us a better way to do the same job. Here is how the code above will be using IHttpActionResult:

public IHttpActionResult Get(int id)
{
    var doc = _documentations[id];
    if (doc==null)
    {
        return NotFound();
    }
    return Ok(doc);
}

Easier to write, easier to read!