Disable chunking in Asp.Net Core

…衆ロ難τιáo~ 提交于 2019-11-26 20:41:44

问题


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.

Is it possible to completely turn off Transfer-Encoding: chunked either at the controller level or in web.config?

EDIT: 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 );
}

回答1:


This took me all day, but I eventually figured out how to get rid of chunking in .Net Core 2.2

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.

Here's the middleware:

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>();

It needs to be before app.UseMvC().




回答2:


In ASP.NET core, this seems to work across hosts:

response.Headers["Content-Encoding"] = "identity";
response.Headers["Transfer-Encoding"] = "identity";

Indicates the identity function (i.e. no compression, nor modification). This token, except if explicitly specified, is always deemed acceptable.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

This also works when you explicitly disable response buffering:

var bufferingFeature = httpContext.Features.Get<IHttpBufferingFeature>();
bufferingFeature?.DisableResponseBuffering();



回答3:


It works in .NET Core 2.0. Just set ContentLength before writing the results into response body stream.

Int startup class:

app.Use(async (ctx, next) =>
{
    var stream = new xxxResultTranslatorStream(ctx.Response.Body);
    ctx.Response.Body = stream;

    await Run(ctx, next);

    stream.Translate(ctx);
    ctx.Response.Body = stream.Stream;
});

Int xxxResultTranslatorStream:

ctx.Response.Headers.ContentLength=40;
stream.Write(writeTargetByte, 0, writeTargetByte.Length);


来源:https://stackoverflow.com/questions/37966039/disable-chunking-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!