如何在 .net 核心中获取 HttpRequest 主体?

How to get HttpRequest body in .net core?

我想在 .net core 中获取 Http Request body,我使用了这段代码:

using (var reader
    = new StreamReader(req.Body, Encoding.UTF8))
{
    bodyStr = reader.ReadToEnd();
}
req.Body.Position = 0

但是我得到了这个错误:

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'FileBufferingReadStream'.

的using语句后出现错误

.net core如何获取HttpRequest Body? 以及如何修复此错误?

使用此扩展方法获取 httpRequest Body:

   public static string GetRawBodyString(this HttpContext httpContext, Encoding encoding)
    {
        var body = "";
        if (httpContext.Request.ContentLength == null || !(httpContext.Request.ContentLength > 0) ||
            !httpContext.Request.Body.CanSeek) return body;
        httpContext.Request.EnableRewind();
        httpContext.Request.Body.Seek(0, SeekOrigin.Begin);
        using (var reader = new StreamReader(httpContext.Request.Body, encoding, true, 1024, true))
        {
            body = reader.ReadToEnd();
        }
        httpContext.Request.Body.Position = 0;
        return body;
    }

The important thing is that HttpRequest.Body is a Stream type And when the StreamReader is disposed, HttpRequest.Body is also disposed.

我一直遇到这个问题,直到我在 GitHub 中找到以下 link: 参考下面link和GetBody方法 https://github.com/devdigital/IdentityServer4TestServer/blob/3eaf72f9e1f7086b5cfacb5ecc8b1854ad3c496c/Source/IdentityServer4TestServer/Token/TokenCreationMiddleware.cs

接受的答案对我不起作用,但我正在阅读正文两次。

    public static string ReadRequestBody(this HttpRequest request, Encoding encoding)
    {
        var body = "";
        request.EnableRewind();

        if (request.ContentLength == null ||
            !(request.ContentLength > 0) ||
            !request.Body.CanSeek)
        {
            return body;
        }

        request.Body.Seek(0, SeekOrigin.Begin);

        using (var reader = new StreamReader(request.Body, encoding, true, 1024, true))
        {
            body = reader.ReadToEnd();
        }

        //Reset the stream so data is not lost
        request.Body.Position = 0;

        return body;
    }

请查看answer by Stephen Wilkinson

.NET Core 3.1

使用以下内容

Startup.cs

app.Use((context, next) =>
{
    context.Request.EnableBuffering(); // calls EnableRewind() `https://github.com/dotnet/aspnetcore/blob/4ef204e13b88c0734e0e94a1cc4c0ef05f40849e/src/Http/Http/src/Extensions/HttpRequestRewindExtensions.cs#L23`
    return next();
});

然后您应该能够按照其他答案倒带:

httpContext.Request.Body.Seek(0, SeekOrigin.Begin);

简单的解决方法:

using (var content = new StreamContent(Request.Body))
{
     var contentString = await content.ReadAsStringAsync();
}