如何在asp net core 2.2中间件中多次读取请求正文? [英] How to read request body multiple times in asp net core 2.2 middleware?
本文介绍了如何在asp net core 2.2中间件中多次读取请求正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过这个:读取请求正文两次和这个:https://github.com/aspnet/Mvc/issues/4962但没有用.我这样阅读请求正文:
I tried this: Read request body twice and this: https://github.com/aspnet/Mvc/issues/4962 but did not work. I read request body like this:
app.Use(async (context, next) =>
{
var requestBody = await ReadStream(context.Request.Body);
var requestPath = context.Request.Path.ToString();
//Do some thing
await next.Invoke();
var responseStatusCode = context.Response.StatusCode;
//Do some other thing
});
private async Task<string> ReadStream(Stream stream)
{
using (var streamReader = new StreamReader(stream))
{
var result = await streamReader.ReadToEndAsync();
return result;
}
}
在控制器中,我得到处置对象"或空流".
In controller I get 'disposed object' or 'empty stream'.
推荐答案
经过一番折腾和使用context.Request.EnableRewind()"它终于像这样工作了:
After some more struggling and use "context.Request.EnableRewind()" it's finally worked like this:
app.Use(async (context, next) =>
{
context.Request.EnableRewind();
var stream = context.Request.Body;
using (var reader = new StreamReader(stream))
{
var requestBodyAsString = await reader.ReadToEndAsync();
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
//Do some thing
await next.Invoke();
var responseStatusCode = context.Response.StatusCode;
//Do some other thing
}
});
这篇关于如何在asp net core 2.2中间件中多次读取请求正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文