如何解决ASP.Net Web API:记录中间件:System.ObjectDisposedException:无法访问封闭的Stream
我正在尝试在asp.net核心Web API应用程序中实现请求-响应日志记录中间件。它在正常流程中工作正常。但是在应用程序中出现异常时,看到ObjectDisposed错误
System.ObjectDisposedException:无法访问关闭的Stream。
以下是代码块:
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestResponseLoggingMiddlewarecs> _logger;
public LoggingMiddleware(RequestDelegate requestDelegate,ILogger<LoggingMiddleware> logger)
{
_next = requestDelegate;
_logger = logger;
}
public async Task Invoke(HttpContext httpContext)
{
httpContext.Request.EnableBuffering();
var body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
_logger.LogInformation($"Body: {body}");
httpContext.Request.Body.Position = 0;
//await _next(context);
var originalBodyStream = httpContext.Response.Body;
using (var responseBody = new MemoryStream())
{
var response = httpContext.Response;
response.Body = responseBody;
await _next(httpContext);
string responseBodyContent = null;
responseBodyContent = await ReadResponseBody(response);
await responseBody.CopyToAsync(originalBodyStream);
_logger.LogInformation(responseBodyContent);
}
}
}
在Startup.cs配置方法中
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseExceptionHandler("/error-developer");
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMiddleware<RequestResponseLoggingMiddlewarecs>();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
}
错误控制器
public class ErrorController : ControllerBase
{
[Route("/error-developer")]
public IActionResult Error([FromServices] IWebHostEnvironment webHostEnvironment)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var ex = context?.Error;
var isDev = webHostEnvironment.IsDevelopment();
return Problem(
detail: context.Error.StackTrace,title: context.Error.Message);
}
[Route("/error")]
public IActionResult Error() => Problem();
}
在处引发异常,以等待responseBody.CopyToAsync(originalBodyStream);
有什么想法/想法吗?
还是实现请求响应日志记录和异常处理的更好方法?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。