Streaming JSON Objects (NDJSON) With HttpClient

13 maj 2021 | Blog | programowanie | c# | .net | async-streams | httpclient | ndjson | IT

My first post on working with NDJSON stream in .NET was a result of a use case I needed to satisfy in one of the projects I'm involved with (and it worked great). As a result, I've received some questions on this subject. I've already answered the most common one on this blog, but there were a couple more that were really frequent. So I've decided I'm going to add a few more posts to this series:

Streaming NDJSON With HttpClient

When I was writing my first post about NDJSON, I didn't know there were services out there using it as an input format. The fact is that they do, which creates a need for a way to stream NDJSON with HttpClient. The natural expectation is to be able to POST an async stream, preferably with simple and elegant code.

async IAsyncEnumerable<WeatherForecast> streamWeatherForecastsAsync()
{
for (int daysFromToday = 1; daysFromToday <= 10; daysFromToday++)
{
WeatherForecast weatherForecast = await GetWeatherForecastAsync(daysFromToday).ConfigureAwait(false);

yield return weatherForecast;
};
};

using HttpClient httpClient = new();

using HttpResponseMessage response = await httpClient.PostAsync("...",
new NdjsonAsyncEnumerableContent<WeatherForecast>(streamWeatherForecastsAsync())
).ConfigureAwait(false);

response.EnsureSuccessStatusCode();

The way to achieve the elegancy in the above snippet is through the custom implemen

POSTY TEGO AUTORA

Monitoring C# Azure Functions in the Isolated Worker Model - Infrastructure & Configuration Deep Dive26 lis 2024

Blog | programowanie | .net | c# | azure functions | IT

ASP.NET Core 9 and IAsyncEnumerable - Async Streaming JSON and NDJSON From Blazor WebAssembly24 wrz 2024

Blog | programowanie | .net | c# | asp.net core | blazor | IT

Azure Functions Extensibility - Extensions and Isolated Worker Model5 mar 2024

Blog | programowanie | .net | c# | azure functions | azure | IT

Azure Functions Extensibility - Runtime Scaling22 lut 2024

Blog | programowanie | .net | c# | azure | IT

Yet Another Developer Blog

noreply@blogger.com (Tomasz Pęczek)