本文介绍了在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中禁用分块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:11