Last active
August 31, 2023 12:38
-
-
Save alexminza/568ab86795f05fb5af44f686ac393106 to your computer and use it in GitHub Desktop.
AsyncEnumerableStringsResult
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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