我有一个错误记录器,可以将错误从 API Controller 写入数据库。它有一些这样的代码:
string form = string.Empty;
if (request.Method == "POST")
{
using (StreamReader sr = new StreamReader(request.Body))
{
if (request.Body.CanSeek) request.Body.Seek(0, SeekOrigin.Begin);
if (request.Body.CanRead) form = sr.ReadToEndAsync().Result;
form = sr.ReadToEndAsync().Result;
}
}
但是,这无法读取正文,因为它已被读取,并且 ASP.NET Core 不允许您这样做。见:https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/
我看了
.EnableBuffering
和 .EnableRewind
但这些都不存在于 HttpRequest
(至少不是在 3.0.app.Use(async (context, next) => {
context.Request.EnableRewind();
await next();
});
如何重新阅读请求正文?
最佳答案
EnableBuffering
存在于 dotnet 3.0 中,只需添加
using Microsoft.AspNetCore.Http;
然后
app.Use(async (context, next) => {
context.Request.EnableBuffering();
await next();
});
关于c# - 在 ASP.NET 核心中重新读取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076409/