读取请求正文中断 ASP.NET Core 2.2 网关中的流程

Reading RequestBody distrupts flow in ASP.NET Core 2.2 gateway

我有一个中间件来跟踪我在 ASP.NET Core 2.2 API 中自定义开发的网关的性能。我使用了 Whosebug 中的

基本上主要部分如下:

public class ResponseRewindMiddleware {
    private readonly RequestDelegate next;

    public ResponseRewindMiddleware(RequestDelegate next) {
        this.next = next;
    }

    public async Task Invoke(HttpContext context) {

        Stream originalBody = context.Response.Body;
        /* MY CODE COMES HERE */

        try {
            using (var memStream = new MemoryStream()) {
                context.Response.Body = memStream;

                await next(context);

                memStream.Position = 0;
                string responseBody = new StreamReader(memStream).ReadToEnd();

                memStream.Position = 0;
                await memStream.CopyToAsync(originalBody);
            }

        } finally {
            context.Response.Body = originalBody;
        }

    } 

这段代码运行正常。但我想将输入(JSON 正文)记录到网关并添加以下行:

using (System.IO.StreamReader rd = new System.IO.StreamReader(context.Request.Body))
{
    bodyStr = rd.ReadToEnd();
}

这从 Request 读取输入正文,但流程中断,流程的其余部分没有流程,导致 "HTTP 500 Internal Server Error"。我假设通过 Stream 读取请求主体会破坏某些东西。

如何在不中断流程的情况下读取请求正文?

思路是调用EnableBuffering开启多读,读完请求体不释放。以下对我有用。

// Enable the request body to be read in the future
context.Request.EnableBuffering();

// Read the request body, but do not dispose it
var stream = new StreamReader(context.Request.Body);            
string requestBody = await stream.ReadToEndAsync();

// Reset to the origin so the next read would start from the beginning
context.Request.Body.Seek(0, SeekOrigin.Begin);