简体   繁体   English

在 ASP.Net Core 3.0 中多次读取正文

[英]Read Body multiple times in ASP.Net Core 3.0

I need to be able to read the body of the request for logging purposes early in a pipeline but I am unable to rewind it back.我需要能够在管道的早期读取请求的主体以进行日志记录,但我无法将其倒回。

Sample code here (thanks to https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/ ):此处的示例代码(感谢https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/ ):

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    context.Request.EnableBuffering();

    // Leave the body open so the next middleware can read it.
    using (var reader = new StreamReader(
        context.Request.Body,
        encoding: Encoding.UTF8,
        detectEncodingFromByteOrderMarks: false,
        bufferSize: bufferSize,
        leaveOpen: true))
    {
        var body = await reader.ReadToEndAsync();
        // Do some processing with body…

        // Reset the request body stream position so the next middleware can read it
        context.Request.Body.Position = 0; <<---- throws exception
    }

    // Call the next delegate/middleware in the pipeline
    await next(context);
}

this throws the following exception when rewinding:倒带时会引发以下异常:

System.ObjectDisposedException: 'IFeatureCollection has been disposed. System.ObjectDisposedException: 'IFeatureCollection 已被释放。 Object name: 'Collection'.' Object 名称:“收藏”。

You will need to copy the body data in a new stream and put it back in the body:您需要将正文数据复制到新的 stream 中并将其放回正文中:

using (var reader = new StreamReader(
        context.Request.Body,
        encoding: Encoding.UTF8,
        detectEncodingFromByteOrderMarks: false,
        bufferSize: bufferSize,
        leaveOpen: true))
{
    var body = await reader.ReadToEndAsync();
    // Do some processing with body

    // Get the body data    
    byte[] bodyData = Encoding.UTF8.GetBytes(body);

    // Put a new stream with that data in the body
    context.Request.Body = new MemoryStream(bodyData);
}

// Call the next delegate/middleware in the pipeline
await next(context);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM