ASP.NET Core 6 Web API流式响应本地正常,Azure Windows应用异常
Azure Web App上ASP.NET Core 6 Web API响应流无法实时返回
我将基于Windows IIS托管的ASP.NET Core 6 Web API部署到Azure Web App后,遇到响应流无法实时接收的问题——返回内容总是以大段形式出现,推测是响应缓冲导致。本地IIS托管时一切正常,仅Azure环境出现此异常。
已尝试的解决措施
- 在中间件中禁用响应缓冲:
var responseBodyFeature = context.Features.Get<IHttpResponseBodyFeature>(); if (responseBodyFeature != null) responseBodyFeature.DisableBuffering();
- 通过web.config添加响应头配置:
<httpProtocol> <customHeaders> <!-- 禁用响应缓冲 --> <add name="Buffer" value="False" /> <add name="X-Accel-Buffering" value="no" /> <add name="Cache-Control" value="no-cache" /> </customHeaders> </httpProtocol>
- 确认不存在APIM或代理引发缓冲问题,API中的流式处理逻辑如下:
await foreach (var streamingResponse in response.Response.WithCancellation(canToken)) { foreach (var choice in streamingResponse.Choices) { yield return await Task.Run(() => choice.Text); await Response.Body.FlushAsync(); } }
- 考虑过以下Kestrel设置,但担心影响非流式端点,暂未启用:
.UseKestrel(options => { options.Limits.MaxResponseBufferSize = 2000 });
客户端调用代码
let config = { 'method': "POST", 'cached': false, headers: { 'Content-Type': 'application/json', 'Authorization': '<token>' }, body: JSON.stringify(requestBody) }; const response = await fetch(url, config); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); while (true) { const { value, done } = await reader.read(); if (done) break; console.log(value); }
内容的提问来源于stack exchange,提问作者singh_v
相关产品推荐
相关产品推荐

