ASP.NETCore中的IAsyncEnumerable<T>在部署于IIS上时不支持流式处理行为?
创始人
2024-09-18 13:30:54
0

可以尝试在部署时使用 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 asyncEnumerable;
    }

    public async Task WriteAsync(OutputFormatterWriteContext context)
    {
        var asyncEnumerable = (IAsyncEnumerable)context.Object;

        using (var responseStream = context.HttpContext.Response.Body)
        {
            await foreach (var item in asyncEnumerable)
            {
                var itemBytes = Encoding.UTF8.GetBytes(item.ToString());
                await responseStream.WriteAsync(itemBytes, 0, itemBytes.Length);
                await responseStream.FlushAsync();
            }
        }
    }
}

最后在控制器中使用 IAsyncEnumerable 订阅器发出

相关内容

热门资讯

透视ai代打!wepoker私... 透视ai代打!wepoker私人辅助器(透视)杭州都莱app有辅助吗(确实存在有辅助插件)-哔哩哔哩...
此事迅速冲上热搜!约局吧德州有... 此事迅速冲上热搜!约局吧德州有挂吗(透视)雀友会广东潮汕麻雀开挂(好像是真的辅助下载)-哔哩哔哩1、...
围绕透视问题!德州机器人代打脚... 围绕透视问题!德州机器人代打脚本(透视)对战互娱怎么开辅助(原来存在有辅助辅助器)-哔哩哔哩1、游戏...
透视挂透视!epoker有透视... 您好,新众乐辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这...
近日!红龙poker有辅助吗(... 近日!红龙poker有辅助吗(透视)新道游辅助软件下载(总是真的有辅助安装)-哔哩哔哩新道游辅助软件...
经调查!破解辅助插件wepok... 经调查!破解辅助插件wepoker(透视)悟空大厅辅助器(果然真的是有辅助辅助器)-哔哩哔哩亲,关键...
据统计!hh poker辅助有... 据统计!hh poker辅助有用吗(透视)创思维辅助器(其实有辅助神器)-哔哩哔哩1、让任何用户在无...
此事备受玩家关注!hhpoke... 此事备受玩家关注!hhpoker有后台操控吗(透视)雀神挂件价格(竟然是有辅助插件)-哔哩哔哩1、雀...
连日来!wepoker辅助器激... 连日来!wepoker辅助器激活码(透视)闲来辅助工具(确实是有辅助工具)-哔哩哔哩1、完成闲来辅助...
透视代打!wepoker底牌透... 透视代打!wepoker底牌透视脚本(透视)潮友会鱼虾蟹怎么发现软件控制(原来存在有辅助下载)-哔哩...