Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

是否支持分块传输返回? #262

Answered by xljiulang
fengb3 asked this question in Q&A
Discussion options

是否支持 Content-Typetext/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; }
 }
}

是否支持这种使用场景?

You must be logged in to vote

服务端使用AsyncEnumerable<Product>,然后客户端接收为HttpResponseMessage即可,HttpResponseMessage的Content支持反序列化为AsyncEnumerable<Product>

Replies: 1 comment

Comment options

服务端使用AsyncEnumerable<Product>,然后客户端接收为HttpResponseMessage即可,HttpResponseMessage的Content支持反序列化为AsyncEnumerable<Product>

You must be logged in to vote
0 replies
Answer selected by fengb3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /