在 ASP.NET Core 中禁用分块

编程入门 行业动态 更新时间:2024-10-24 14:27:04
本文介绍了在 ASP.NET Core 中禁用分块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 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 中禁用分块

本文发布于:2023-11-14 04:44:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!