我有一个简单的中间件,它获取请求的主体并将其存储在一个字符串中。它正在读取流,但问题是它不会调用我的 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/