Question: What is wrong with the following ASP.NET Core controller:
No idea?
Take a look at the return type...
Returning IEnumerable
ToListAsync
before returning the result:
IAsyncEnumerable<T>
. This no longer results in synchronous iteration and is as efficient as returning IEnumerable<T>
.
Let’s rewrite the example above to use IAsyncEnumerable<T>
:
REMARK: If we take a look at the original example again, it will not be an issue in ASP.NET Core 3.0 or higher. Why? Because we allow the framework to choose how to handle the IQueryable<T> we get back from the Where() clause. In the situation we are using ASP.NET Core 3.0 or higher the results will be buffered and correctly provided to the serializer. However this is implicit behavior that doesn’t work in all situations(it depends on the underlying types used).
More information and other performance tips can be found here: https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices