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

Azure APIM中流式响应失效问题咨询及配置需求

解决Azure APIM代理Dotnet流式API时响应合并问题

问题描述

Dotnet编写的流式API直接通过App Service访问时,能正常逐段返回响应;但通过Azure APIM路由调用时,所有响应内容会被合并为单个chunk返回,流式效果失效。

相关代码与测试命令

API实现代码

[Route("[controller]")]
[ApiController]
public class NewStreamingController : ControllerBase
{
    [HttpPost("NewStream")]
    public async Task GetStream([FromBody] MasterInput request)
    {
        for (var counter = 0; counter < request.Count; counter++)
        {
            var message = $"data - {counter} \n";
            await Response.WriteAsync(message);
            await Response.Body.FlushAsync();
            await Task.Delay(50);
        }
    }

    public class MasterInput
    {
        public int Count { get; set; }
    }
}

本地测试curl命令

curl -X "POST"  "https://localhost:7152/NewStreaming/NewStream"   -H "accept: */*"   -H "Content-Type: application/json"   -d "{ \"count\": 15 }"

解决步骤:配置Azure APIM支持流式传输

Azure APIM默认会缓冲响应内容,需通过以下配置禁用缓冲,开启流式支持:

1. 操作级策略配置

登录Azure APIM门户,定位到目标API的NewStream操作,进入策略编辑页面,添加以下出站策略:

<outbound>
    <!-- 禁用响应缓冲,允许流式传递 -->
    <response-buffering policy="disable" />
    <!-- 确保Transfer-Encoding头为chunked,覆盖可能的后端或APIM默认设置 -->
    <set-header name="Transfer-Encoding" exists-action="override">
        <value>chunked</value>
    </set-header>
</outbound>

2. 后端API优化

在Dotnet API的GetStream方法开头添加以下代码,明确告知响应为分块传输:

Response.Headers.TransferEncodingChunked = true;
// 避免设置Content-Length,流式响应无法提前确定总长度
Response.ContentLength = null;

3. 排查全局策略冲突

若操作级配置未生效,检查APIM全局策略(路径:API管理 > 策略 > 全局策略),确保没有全局的response-buffering设置为enable,避免覆盖操作级配置。

验证

配置完成后,使用curl调用APIM端点验证:

curl -X "POST"  "https://{你的APIM实例名}.azure-api.net/NewStreaming/NewStream"   -H "accept: */*"   -H "Content-Type: application/json"   -H "Ocp-Apim-Subscription-Key: {你的订阅密钥}"   -d "{ \"count\": 15 }"

此时应能看到响应内容每隔约50ms返回一段,而非一次性返回所有数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:41:04