我正试图在OnActionExecuting方法中读取请求体,但我总是null为身体做准备.
var request = context.HttpContext.Request;
var stream = new StreamReader(request.Body);
var body = stream.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
我试图将流位置显式设置为0,但这也不起作用.由于这是ASP.NET CORE,我认为事情没有什么不同.我可以在这里看到所有的示例,指的是旧的webapi版本.
有没有其他方法这样做?
我编写了在服务器方法调用后运行的过滤器,并将其内容打印到控制台。代码是用ASP.NET core v2.1编写的:
public class MyCustomFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{
// ERROR on the next line!
using (StreamReader sr = new StreamReader(context.HttpContext.Response.Body))
{
Console.WriteLine(sr.ReadToEnd());
}
base.OnResultExecuted(context);
}
}
Run Code Online (Sandbox Code Playgroud)
结果-异常:
流不可读。
进一步的调查使我发现流 ( context.HttpContext.Response) 具有这些值:
这可以解释为什么它无法读取正文......
怎么解决?