【发布时间】:2020-03-11 23:19:54
【问题描述】:
我最近将一个 API 升级到 .NET Core 3,据我所知,升级后该位停止工作。
我想记录异常和通过请求正文传入的 json 有效负载。此 ExceptionLogger 作为过滤器插入以全局处理错误:
public class ExceptionLogger
{
private readonly IServiceScopeFactory _factory;
public ExceptionLogger(IServiceScopeFactory factory)
{
_factory = factory;
}
public async Task<Guid?> LogException(Exception ex)
{
using var scope = _factory.CreateScope();
var accessor = scope.ServiceProvider.GetRequiredService<IHttpContextAccessor>();
var displayUrl = accessor?.HttpContext?.Request?.GetDisplayUrl();
var payload = await RetrievePayload(accessor, displayUrl);
// ... code proceeds to log the exception, including the payload.
}
private async Task<string> RetrievePayload(IHttpContextAccessor accessor, string displayUrl)
{
accessor.HttpContext.Request.EnableBuffering();
accessor.HttpContext.Request.Body.Seek(0, System.IO.SeekOrigin.Begin);
using var sr = new System.IO.StreamReader(accessor.HttpContext.Request.Body);
return await sr.ReadToEndAsync(); // The request body is always empty now....!
}
}
accessor 有查询字符串和表单参数,甚至accessor.HttpContext.Request.ContentLength 也有一个值表明有效负载在那里。但是,Request.Body 流是空的,即使在我重置光标位置之后也是如此。
此时我如何获取请求正文?
【问题讨论】:
标签: c# asp.net-core .net-core-3.0