Search code examples
c#asp.netasp.net-web-apiasync-awaitasp.net-web-api2

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


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> ?


Solution

  • 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.