pcd2iq
Last Updated: February 25, 2016
·
10.77K
· 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!