Skip to content

Instantly share code, notes, and snippets.

@alexminza
Last active August 31, 2023 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexminza/568ab86795f05fb5af44f686ac393106 to your computer and use it in GitHub Desktop.
Save alexminza/568ab86795f05fb5af44f686ac393106 to your computer and use it in GitHub Desktop.
AsyncEnumerableStringsResult
//https://stackoverflow.com/questions/76106284/how-to-return-chunked-text-plain-content-from-web-api-using-minimal-api
//https://github.com/dotnet/aspnetcore/tree/main/src/Http/Http.Results
public class AsyncEnumerableStringsResult : IResult, IContentTypeHttpResult, IStatusCodeHttpResult
{
protected readonly IAsyncEnumerable<string> chunks;
public string? ContentType => "text/plain; charset=utf-8";
public int StatusCode => StatusCodes.Status200OK;
int? IStatusCodeHttpResult.StatusCode => StatusCode;
public AsyncEnumerableStringsResult(IAsyncEnumerable<string> chunks) => this.chunks = chunks ?? throw new ArgumentNullException(nameof(chunks));
public async Task ExecuteAsync(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));
httpContext.Response.ContentType = this.ContentType;
httpContext.Response.StatusCode = this.StatusCode;
await foreach (var chunk in this.chunks)
if (!string.IsNullOrEmpty(chunk))
await httpContext.Response.WriteAsync(chunk, cancellationToken: httpContext.RequestAborted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment