问题描述
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next,ILogger<ExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
httpContext.Request.EnableBuffering();
var body = string.Empty;
// Leave the body open so the next middleware can read it.
using (var reader = new StreamReader(
httpContext.Request.Body,encoding: Encoding.UTF8,detectEncodingFromByteOrderMarks: false,bufferSize: 1024,leaveOpen: true))
{
body = await reader.ReadToEndAsync();
httpContext.Request.Body.Position = 0;
}
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext,body,ex);
}
}
private async Task HandleExceptionAsync(HttpContext context,string body,Exception exception)
{
LogInfrastructure log = new LogInfrastructure
{
Source = "Test",Module = "Test.Module",Event = exception.TargetSite?.Name,};
var _serializedLog = JsonConvert.SerializeObject(log);
if (log.Level == LogLevel.Warning)
_logger.LogWarning(_serializedLog);
else
_logger.LogError(_serializedLog);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await Task.CompletedTask;
}
Event
中的属性 LogInfrastructure
应设置为引发异常的方法的名称,例如 Stack Trace 中的方法描述
"StackTrace": " at WebApi.Controllers.TestController.GetAll() in C:\\Microservice\\WebApi\\Controllers\\TestController.cs:line 39\r\n
,但 ex.TargetSite.Name
的返回值为 MoveNext
。
如何返回 WebApi.Controllers.TestController.GetAll()
而不是 MoveNext
?
我也试过了,但返回值与 exception.TargetSite?.Name
private string GetEvent(Exception ex)
{
var _event = string.Empty;
if(!string.IsNullOrEmpty(ex.StackTrace))
{
StackTrace trace = new StackTrace(ex,true);
StackFrame stackFrame = trace.GetFrame(trace.FrameCount - 1);
_event = stackFrame.getmethod().Name;
}
return _event;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)