可以尝试在部署时使用 Microsoft.AspNetCore.Server.Kestrel NuGet 包,并在 Startup.cs 中配置应用程序并设置支持流式处理的响应头。以下是示例代码:
在 ConfigureServices 中添加以下代码:
services.AddControllers().AddNewtonsoftJson();
services.AddHttpContextAccessor();
services.AddResponseCompression();
// 添加 Kestrel 选项并设置最大响应缓存(单位:字节)
services.Configure(options =>
{
options.Limits.MaxResponseBufferSize = 10 * 1024 * 1024; // 10MB
});
// 添加 MVC 中间件以支持控制器
services.AddMvc(options =>
{
// 设置流式处理响应头
options.OutputFormatters.Add(new StreamOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("stream", "application/octet-stream");
});
在 Configure 方法中添加以下代码:
// 启用响应压缩中间件
app.UseResponseCompression();
// 添加控制器路由
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
添加一个自定义的流式输出格式化器 StreamOutputFormatter.cs,用于将 IAsyncEnumerable 内容流式输出:
public class StreamOutputFormatter : IOutputFormatter
{
public string ContentType { get; } = "application/octet-stream";
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return context.Object is IAsyncEnumerable
最后在控制器中使用 IAsyncEnumerable 订阅器发出