【问题标题】:Reading RequestBody distrupts flow in ASP.NET Core 2.2 gateway读取请求正文会中断 ASP.NET Core 2.2 网关中的流程
【发布时间】:2020-05-04 02:44:13
【问题描述】:

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

基本上主要部分如下:

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 内部服务器错误”。我假设通过 Stream 读取请求正文会破坏某些内容。

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

【问题讨论】:

标签: asp.net-core middleware gateway


【解决方案1】:

这个想法是调用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2021-10-13
    • 2020-07-23
    相关资源
    最近更新 更多