Читать тело несколько раз в ASP. Net Core 3.0 - PullRequest
0 голосов
/ 20 апреля 2020

Мне нужно иметь возможность прочитать тело запроса для регистрации в начале конвейера, но я не могу перемотать его обратно.

Пример кода здесь (спасибо 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);
}

это вызывает следующее исключение при перемотке:

Система .ObjectDisposedException: 'IFeatureCollection был удален. Имя объекта: «Коллекция». '

1 Ответ

1 голос
/ 20 апреля 2020

Вам нужно будет скопировать данные тела в новый поток и поместить их обратно в тело:

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);
...