c# - 从 asp.net core 2.0 中的中间件获取 HttpContext 中的请求正文

标签 c# asp.net-core-2.0

我有一个简单的中间件,它获取请求的主体并将其存储在一个字符串中。它正在读取流,但问题是它不会调用我的 Controller ,它在我读取流并抛出错误后立即调用

A non-empty request body is required

.下面是我的代码。

  public async Task Invoke(HttpContext httpContext)
            {
                var timer = Stopwatch.StartNew();
                ReadBodyFromHttpContext(httpContext);
                await _next(httpContext);
                timer.Stop();
            }

   private string ReadBodyFromHttpContext(HttpContext httpContext)
        {
           return await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
        }

最佳答案

您需要将 HttpContext.Request.Body 从仅向前的内存流转换为可搜索的流,如下所示。

//  Enable seeking
context.Request.EnableBuffering();
//  Read the stream as text
var bodyAsText = await new System.IO.StreamReader(context.Request.Body).ReadToEndAsync();
//  Set the position of the stream to 0 to enable rereading
context.Request.Body.Position = 0; 

关于c# - 从 asp.net core 2.0 中的中间件获取 HttpContext 中的请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47624938/

相关文章:

asp.net - <access sslFlags ="Ssl.SslRequireCer"> 在 .net 核心

c# - 如何从 Microsoft.AspNetCore.All 元包中删除额外的引用

c# - 具有 Windows 身份验证的 ASP.NET Core 2.1 自定义 RoleProvider

c# - 我的 C# 应用程序将 0xE0434352 返回到 Windows 任务计划程序,但它没有崩溃

c# - Asp.Net Core 2.2 中 MvcJsonOptions 的 AddJsonOptions

javascript - HTML 页面上的 Google Cloud Speech API

c# - 批量注册开放通用实现

c# - 使用 LINQ 执行更新

asp.net - 如何在Vs code中使用命令行设置asp.net core启动项目

asp.net-core-2.0 - UseHangfireServer 抛出异常