Returning IHttpActionResult vs IEnumerable<Item> vs IQueryable<Item>

Adam Szabo picture Adam Szabo · Apr 21, 2014 · Viewed 16.3k times · Source

In ASP.NET Web API 2, what is the difference among the following?

public async Task<IEnumerable<MyItem>> GetMyItems()
{
    //... code ..., var myItems = await ...
    return myItems;
}

and

public async Task<IQueryable<MyItem>> GetMyItems()
{
    //... code ..., var myItems = await ...
    return myItems;
}

and

public async Task<IHttpActionResult> GetMyItems()
{
    //... code ..., var myItems = await ...
    return Ok(myItems);
}

Should I return IHttpActionResult or IEnumerable<MyItem> / IQueryable<MyItem> ?

Answer

turhanco picture turhanco · Aug 19, 2014

You should return IHttpActionResult because you can be more specific to the client. You can create more user friendly web applications. Basically you can return different HTML status messages for different situations.

For example:

public async Task<IHttpActionResult> GetMyItems()
{
    if(!authorized)
        return Unauthorized();
    if(myItems.Count == 0)
        return NotFound();
    //... code ..., var myItems = await ...
    return Ok(myItems);
}

IEnumerableand IQueryable will just parse your data into the output format and you will not have a proper way to handle exceptions. That is the most important difference.