4
votes

Consider the following two pieces of code. Both return data to a Web API Get call. Both return a list of items. Both work. The first one was taken from Visual Studio starter Blazor Wasm App. The second one was taken from an online tutorial. tblTitles is a table in a remote database, accessed through _dataContext.

Which of these should be used and why? Or perhaps one suits better for a specific situation?

    [HttpGet]
    //First method:
    public IEnumerable<TitlesTable> Get()
    {
        var titles =  _dataContext.tblTitles.ToList();
        return titles;
    }

    //Second method:
    public async Task<IActionResult> Get()
    {
        var titles = await _dataContext.tblTitles.ToListAsync();
        return Ok(titles);
    }
3

3 Answers

5
votes

I believe you're noticing the different available controller return types. From that docs page:

ASP.NET Core offers the following options for web API controller action return types:

  • Specific type
  • IActionResult
  • ActionResult<T>

The page offers considerations of when to use each.

5
votes

There are 2 differences between your snippets, they should be considered separately.

1. Sync or Async

Most actions do some I/O and the async/await patterns is much preferred for handling that, it will allow your server to handle much more concurrent requests.

2. Plain data or IActionResult

Returning data directly is asking ASP.NET to wrap it in a response for you. That is easy but as soon as you try to add validations it becomes problematic. Any error will be returned as status 500 (Internal server error), a well designed API should be able to return 400 (Bad request) or 404 (Not Found) when applicable.

So, in conclusion, async Task<IActionResult> or async Task<ActionResult<T>> are the best patterns for a Controller Action.


The first one was taken from Visual Studio starter Blazor Wasm App.

No, it wasn't. The demo controller generates some weatherdata but does not do any I/O.

Which makes the chosen short form acceptable, but consider it to be of 'demo' quality level.

3
votes

Both are the same. By default, asp .net treats action methods as HttpGet if no attribute is specified. Now both return a list, but you should consider as well to return a specific status code as part of your api. In that way the client application can understand what happened with the request

IMHO, I will go with this approach for your api

[HttpGet]
 public async Task<IActionResult> Get()
 {
    var titles = await _dataContext.tblTitles.ToListAsync();
    return Ok(titles);
 }

You can return a specific type instead of an IActionResult which is the generic representation but you are only going to see advantage of that when you need to generate the documentation for you api using the open api standard. Packages like swashbuckle inspect via reflection the return type to generate the proper output model on the documentation. Hope this helps