从ASP.NET Core 2.0中的中间件获取HttpContext内部的请求正文 [英] getting the request body inside HttpContext from a Middleware in asp.net core 2.0
本文介绍了从ASP.NET Core 2.0中的中间件获取HttpContext内部的请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的中间件,可获取请求的主体并将其存储在字符串中.它可以很好地读取流,但问题是它不会调用我的控制器,而该控制器在我读取流并抛出错误后立即调用
I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which called just after I read the stream and throw the error
需要一个非空的请求正文
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从仅转发内存流转换为可搜索流,如下所示.
You need to convert HttpContext.Request.Body from a forward only memory stream to a seekable stream, shown below.
// 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;
这篇关于从ASP.NET Core 2.0中的中间件获取HttpContext内部的请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文