简体   繁体   中英

How to send IAsyncEnumerator from WebAPI and stream data through HttpClient in C# 8+?

Examples exist to read data from an IAsyncEnumerator to the UI in a Blazor app using an internal service. Examples also exist on how to send an IAsyncEnumerator as an output from a Web API Controller action.

I haven't seen any examples yet how to read an IAsyncEnumerator stream from an API using an HttpClient within a client like Blazor or Xamarin. Everything I've tried so far, only returns the HttpResponseMessage on the client after the async/await foreach loop on the API is done.

HttpResponseMessage response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

What should the content type be (Produces attribute) on the HttpGet action? What should the Accept value be on the request header from the HttpClient?

[HttpGet]
[Produces("application/json")]
public async IAsyncEnumerable<Data> Get(CancellationToken cancellationToken)
{
    var dbSet = _dbContext.TableName.AsNoTracking().AsAsyncEnumerable().WithCancellation(cancellationToken).ConfigureAwait(false);
    await foreach (var i in dbSet.ConfigureAwait(false))
    {
        var item = new Data
        {
            Id = i.Id,
            Name = i.Name
        };
        yield return item;
    }
}

You'd better not do it with raw http 1.1 request-response model, which is not designed for this, and streaming objects are different from downloading files. With websocket or http2.0 that support multiplexing, you can serialize each elements produced by the IAsyncEnumerable and deserialize them in the client. But still this is manually controlled and not worth. You could use gRPC which is officially supported by ASP.NET Core and supports object streaming. It also supports many more languages and has strongly typed interface definition in comparison with SignalR which supports JavaScript/.NET/Java only and.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM