簡體   English   中英

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

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

我需要能夠在管道的早期讀取請求的主體以進行日志記錄,但我無法將其倒回。

此處的示例代碼(感謝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);
}

倒帶時會引發以下異常:

System.ObjectDisposedException: 'IFeatureCollection 已被釋放。 Object 名稱:“收藏”。

您需要將正文數據復制到新的 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