[解决]Acton拦截器读取body内容后,方法内无法读取到body内容

注意:

1、在拦截器处理Stream时,应避免使用using语句包裹StreamReader,因为这会导致Stream在读取完成后关闭,进而阻止后续的读取尝试

2、考虑到性能和稳定性,应尽可能使用异步方法读取Stream

reader.ReadToEndAsync()

3、当在拦截器中读取并处理Body后,记得将Stream位置重置

 context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

 

解决后完整代码

1、开启请求体缓存:这样即便在拦截器中读取了Body,也不会影响Controller中的二次读取

app.Use(next => context =>
{
    context.Request.EnableBuffering();
    return next(context);
});

2、过滤器中代码

 var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8);
 string body = await reader.ReadToEndAsync();
 context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

 3、方法内读取

 using var reader = new StreamReader(Request.Body, Encoding.UTF8);
 string body = await reader.ReadToEndAsync();

 

posted @ 2024-07-04 11:46  10:00  阅读(1)  评论(0编辑  收藏  举报