Exploring Neon as a Serverless Postgres Alternative for .NET Applications on Azure - Part 1 (Simple ASP.NET Core on App Service)10 lut 2025
Blog | programowanie | .net | c# | azure | IT
Recently I've published code and written posts about working with asynchronous streaming data sources over HTTP using NDJSON. One of the follow-up questions I've received was how does it relate to async streaming coming in ASP.NET Core 6. As the answer isn't obvious, I've decided to describe the subject in more detail.
Since ASP.NET Core 3, IAsyncEnumerable can be returned directly from controller actions.
[Route("api/[controller]")]
[ApiController]
public class WeatherForecastsController : Controller
{
...
[HttpGet("weather-forecast")]
public IAsyncEnumerable<WeatherForecast> GetWeatherForecastStream()
{
async IAsyncEnumerable<WeatherForecast> streamWeatherForecastsAsync()
{
for (int daysFromToday = 1; daysFromToday <= 10; daysFromToday++)
{
WeatherForecast weatherForecast = await _weatherForecaster.GetWeatherForecastAsync(daysFromToday);
yield return weatherForecast;
};
};
return streamWeatherForecastsAsync();
}
}
The ASP.NET Core will iterate IAsyncEnumerable in an asynchronous manner, buffer the result, and send it down the wire. The gain here is no blocking of calls and no risk of thread pool starvation, but there is no streaming of data to the client. If one would like to test this by making some requests, a possible first attempt could look like this.
private static async Task ConsumeJsonStreamAsync()
{
Console.WriteLine($"[{DateTime.UtcNow:hh:mm:ss.fff}] Receving weather forecasts . . .");
using HttpClientnoreply@blogger.com (Tomasz Pęczek)