我想在asp.net core 3.0应用程序中反序列化httpRequest.Body
两次:一次在中间件内部,第二次在模型绑定期间。
这里是中间件的代码
var streamReader = new StreamReader(httpRequest.Body)
var body = streamReader.ReadToEndAsync();
//some body processing
我的绑定代码中完全相同
根据最佳实践,我需要在此处放置StreamReader
对象。但是,如果我将其部署在中间件中,则在绑定期间会出现异常-Cannot access a disposed object.
,因为StreamReader
也将处置使用过的Stream
。
所以我应该在这里做什么?不要丢弃StreamReader
并允许GC在将来使用吗?
也许这是众所周知且琐碎的,但我完全感到困惑...
感谢@Damien_The_Unbeliever提供的帮助和链接,以下代码将使我们可以处置StreamReader
,而避免了Stream
处置和遵循模型绑定中的异常。
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
context.Request.EnableBuffering();
// Leave the body open so the next middleware can read it.
using (var reader = new StreamReader(
context.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: bufferSize,
leaveOpen: true))
{
var body = await reader.ReadToEndAsync();
// Do some processing with body…
// Reset the request body stream position so the next middleware can read it
context.Request.Body.Position = 0;
}
// Call the next delegate/middleware in the pipeline
await next(context);
}