在ASP.NET Core中禁用分块

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

我正在使用ASP.NET Core Azure Web App向客户端提供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中的分块

This took me all day, but I eventually figured out 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); } } }

然后将其添加到启动中:

Then add this in Startup:

app.UseMiddleware<DeChunkerMiddleware>();

必须在app.UseMvC()之前.

更多推荐

在ASP.NET Core中禁用分块

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

发布评论

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

>www.elefans.com

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