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

时间:2018-10-23 10:26:09

标签: c# asp.net-core streamreader httpcontext

我想在.net核心中获取Http Request正文,我使用了以下代码:

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

但是我得到了这个错误:

  

System.ObjectDisposedException:无法访问已处置的对象。   对象名称:“ FileBufferingReadStream”。

该行的using语句后发生错误

如何在.net核心中获取HttpRequest主体? 以及如何解决此错误?

4 个答案:

答案 0 :(得分:4)

使用此扩展方法获取httpRequest正文:

   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;
    }
  

重要的是HttpRequest.Body是Stream类型,并且在处理StreamReader时,也在处理HttpRequest.Body。

我遇到了这个问题,直到我在github中找到以下链接: 请参阅下面的链接和GetBody方法 https://github.com/devdigital/IdentityServer4TestServer/blob/3eaf72f9e1f7086b5cfacb5ecc8b1854ad3c496c/Source/IdentityServer4TestServer/Token/TokenCreationMiddleware.cs

如果正确,请标记为正确答案。

答案 1 :(得分:0)

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

    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;
    }

答案 2 :(得分:0)

简单的解决方法:

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

答案 3 :(得分:-1)

请在answer前查看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);