![](/img/trans.png)
[英].NET Core 3.1 Exception thrown in controller is logged before hitting middleware
[英]Get request body after exception in middleware. .NET Core 3.1
我需要在ExceptionHandlingMiddleware
中获取异常后的请求正文。 在异常之前我得到简单的请求正文,但在我不能之后。 下面来自ExceptionHandlingMiddleware
的部分代码。
try
{
await _next.Invoke(context);
}
catch (Exception exception)
{
RequestBody = await FormatRequest(context.Request);
}
private async Task<string> FormatRequest(HttpRequest request)
{
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString}
{bodyAsText}";
}
结果,我得到了这个
我试图通过这种方式让身体try
try
{
RequestBody = await FormatRequest(context.Request);
await _next.Invoke(context);
}
它有效,我得到正常json
数据,但我有一个例外,我的 model 无效,因为它是空的。
我试着做request.EnableBuffering();
在例外之前,但这对我没有帮助。
因此,如果我尝试在异常后获取正文,我将无法解析它。 如果我在异常之前得到它,我在 controller 中的 model 无效。
登录ExceptionHandlingMiddleware
出现异常后,如何获取我的 model ?
通常Request.Body
不支持倒带,所以只能读取一次。 临时解决方法是在调用EnableBuffering
后立即拉出正文,然后将 stream 倒回 0 并且不处理它:
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
request.Body.Position = 0; //rewinding the stream to 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.