是否支持分块传输返回? #262
-
| 是否支持
以下为可能的服务端实现: [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { private readonly DbContext _myDbContext; public MyController(DbContext myDbContext) { _myDbContext = myDbContext; } [HttpGet("products/chunked")] public async Task GetResponse([FromQuery] decimal maxPrice, [FromQuery] decimal minPrice) { Response.ContentType = "text/event-stream"; var priceData = _myDbContext.Set<Product>() .Where(p => p.Price<= maxPrice && p.Price >= minPrice) .AsAsyncEnumerable(); // priceData 会筛选出大量结果, 逐步返回结果 await foreach (var data in priceData) { var json = JsonSerializer.Serialize(data); await Response.Body.WriteAsync(Encoding.UTF8.GetBytes($"data: {json}\n\n")); await Response.Body.FlushAsync(); } } public record Product { public string Code { get; set; } public decimal Price { get; set; } public DateTimeOffset Timestamp { get; set; } } }是否支持这种使用场景? |
Beta Was this translation helpful? Give feedback.
Answered by xljiulang Jul 9, 2024
Replies: 1 comment
-
| 服务端使用 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by fengb3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
服务端使用
AsyncEnumerable<Product>,然后客户端接收为HttpResponseMessage即可,HttpResponseMessage的Content支持反序列化为AsyncEnumerable<Product>