asp.net-core - 在 ASP.NET Core 中禁用分块

标签 asp.net-core asp.net-core-mvc azure-web-app-service

我使用 ASP.NET Core Azure Web 应用向客户端提供 RESTful API,但客户端无法正确处理分块。

是否可以在 Controller 级别或文件 web.config 中完全关闭 Transfer-Encoding: chunked

我返回的 JsonResult 有点像这样:

[HttpPost]
[Produces("application/json")]
public IActionResult Post([FromBody] AuthRequest RequestData)
{
    AuthResult AuthResultData = new AuthResult();

    return Json(AuthResultData);
}

最佳答案

如何摆脱 .NET Core 2.2 中的分块:

诀窍是将响应正文读入您自己的MemoryStream,这样您就可以获得长度。完成此操作后,您可以设置 content-length header ,IIS 不会对其进行分块。我认为这也适用于 Azure,但我还没有测试过。

这是中间件:

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 - 在 ASP.NET Core 中禁用分块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966039/

相关文章:

c# - .Net Core 3 控制台无法从 appsettings 获取连接字符串

c# - IL 格式错误 - 奇怪的 .NET 错误

asp.net-core - ASP.NET 5 中 request.Properties 的模拟是什么

asp.net-core - 在 ASP.NET Core 中使用 Entity Framework Core 从 SQL Server 数据库启动应用程序期间加载应用程序范围的设置

ASP.Net5 Startup.cs ConfigurationBuilder

.net-core - 在 .netcore web api 项目中将 null 值传递给 web api 调用中的可为空属性时出现问题

asp.net-mvc - MVC 6 中 @Scripts.Render 的替代品是什么

c# - ASP.Net Core 中的模板化

c# - 使用 ASP.NET Core 6 Minimal API 停止 Azure 中的 Web 应用程序时,不会调用 BackgroundService StopAsync

azure - 将 EntityRecognitionSkill 限制为confidence > .5