.net6.0在ActionFilter中取Request.Body遇到的一些坑

1,260次阅读
没有评论

共计 432 个字符,预计需要花费 2 分钟才能阅读完成。

1. 在 Program.cs 中插入

app.Use(async (context, next) => {
context.Request.EnableBuffering();
await next.Invoke();
});

如果是在 ActionFilter 里使用

context.HttpContext.Request.EnableBuffering();

最后拿到的 Body 就会是空字符串。需要在中间件里使用,原因未知

2.ActionFilter 拿 body

string body;// 重置 RequestBody 的 Position 为 0 
context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8))
{
body = await reader.ReadToEndAsync();
}

正文完
 18
TheStars
版权声明:本站原创文章,由 TheStars 于2024-05-19发表,共计432字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)

星光博客

随机文章