我正在使用 ASP.NET Core Azure Web 应用程序向客户端提供 RESTful API,但客户端无法正确处理分块.
I'm using an ASP.NET Core Azure Web App to provide a RESTful API to a client, and the client doesn't handle chunking correctly.
是否可以在控制器级别或文件 web.config 中完全关闭 Transfer-Encoding: chunked?
Is it possible to completely turn off Transfer-Encoding: chunked, either at the controller level or in file web.config?
我返回的 JsonResult 有点像这样:
I'm returning a JsonResult somewhat like this:
[HttpPost] [Produces("application/json")] public IActionResult Post([FromBody] AuthRequest RequestData) { AuthResult AuthResultData = new AuthResult(); return Json(AuthResultData); } 推荐答案如何在 .NET Core 2.2 中摆脱分块:
How to get rid of chunking in .NET Core 2.2:
诀窍是将响应正文读入您自己的MemoryStream,这样您就可以获得长度.完成此操作后,您可以设置 content-length 标头,IIS 不会对其进行分块.我认为这也适用于 Azure,但我还没有测试过.
The trick is to read the response body into your own MemoryStream, so you can get the length. Once you do that, you can set the content-length header, and IIS won't chunk it. I assume this would work for Azure too, but I haven't tested it.
这是中间件:
public class DeChunkerMiddleware { private readonly RequestDelegate _next; public DeChunkerMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; long length = 0; context.Response.OnStarting(() => { context.Response.Headers.ContentLength = length; return Task.CompletedTask; }); await _next(context); // If you want to read the body, uncomment these lines. //context.Response.Body.Seek(0, SeekOrigin.Begin); //var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); length = context.Response.Body.Length; context.Response.Body.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); } } }然后在启动中添加:
app.UseMiddleware<DeChunkerMiddleware>();需要在app.UseMvC()之前.
更多推荐
在 ASP.NET Core 中禁用分块
发布评论