You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core IAsyncEnumerable流式处理在Windows版Azure App Service失效

IAsyncEnumerable JSON流式返回在Azure Web App(IIS)上失效的问题

在ASP.NET中使用IAsyncEnumerable实现了流式返回逻辑,前端通过JavaScript以流的方式消费数据。本地Kestrel开发环境下代码可正常流式返回结果,但部署到Windows版Azure App Service后,仅第一个项能实时返回,剩余处理完成的项需等待全部任务处理完毕后才会一次性返回。

控制器代码

[HttpPost, Route("runLongProcess")]
[TextJsonFormatter]
public async IAsyncEnumerable<string> RunLongProcess(int id)
{
   await foreach (var item in longProcessTask.RunLongProcess(id))
        yield return item;
}

任务逻辑代码

public async IAsyncEnumerable<string> RunLongProcess(int id)
{
    var pipeline = parentPipeline ?? GetPipeline();
    var resultToProcess = await GetAllResult(id);
    foreach (var item in resultToProcess)
    {
        string processResult = await ProcessItem(item);
        yield return processResult;
    }
}

自定义格式化器特性代码

控制器上的TextJsonFormatter特性用于强制使用System.Text.Json序列化器,代码如下:

public class TextJsonFormatterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
        {
            var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
            objectResult.Formatters.RemoveType<NewtonsoftJsonOutputFormatter>();
            objectResult.Formatters.Add(new SystemTextJsonOutputFormatter(options));
        }
        else
        {
            base.OnActionExecuted(context);
        }
    }
}

内容的提问来源于stack exchange,提问作者Ghassan Karwchan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:03:16