-
Notifications
You must be signed in to change notification settings - Fork 450
是否支持分块传输返回?
#262
-
是否支持 Content-Type 为 text/event-stream 的分块传输返回?
参考使用场景
- 大语言模型API 逐字返回文本容.
- 数据库大量查询时, 逐步返回查询结果
以下为可能的服务端实现:
[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.
All reactions
Answered by
xljiulang
Jul 9, 2024
服务端使用AsyncEnumerable<Product>,然后客户端接收为HttpResponseMessage即可,HttpResponseMessage的Content支持反序列化为AsyncEnumerable<Product>
Replies: 1 comment
-
服务端使用AsyncEnumerable<Product>,然后客户端接收为HttpResponseMessage即可,HttpResponseMessage的Content支持反序列化为AsyncEnumerable<Product>
Beta Was this translation helpful? Give feedback.
All reactions
0 replies
Answer selected by
fengb3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment