我正在尝试创建自定义的异常处理中间件。类似于-> app.UseExceptionHandler(“ / Error”)。我将错误记录在中间件中,然后我要调用错误页面。 问题是,当我进行重定向时,context.Features.Get()中的IExceptionHandlerFeature对象为NULL。 似乎在执行Razorpage时清除了上下文异常。在原始的中间件中,它以某种方式起作用。
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILoggerFactory _loggerFactory;
public ExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
var logger = _loggerFactory.CreateLogger("Serilog Global exception logger");
logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Redirect("/ErrorHandling/Error");
await Task.CompletedTask;
}
}
这是我的Razor错误页面模型
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
private ILogger<ErrorModel> _logger;
public string RequestId { get; set; }
public string ExceptionPath { get; set; }
public string ExceptionMessage { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet(string executionPath)
{
var httpCtx = HttpContext;
var exceptionDetails = httpCtx.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionDetails != null)
{
_logger.LogError(httpCtx.Response.StatusCode, exceptionDetails.Error, exceptionDetails.Error.Message);
//Add data for view
ExceptionPath = exceptionDetails.Path;
ExceptionMessage = "An unexpected fault happened. Try again later.";
}
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
重定向后,httpCtx.Features.Get()应该返回IExceptionHandlerPathFeature对象,但它返回NULL
答案 0 :(得分:0)
从ExceptionHandlerMiddleware和ExceptionHandlerExtensions的源代码开始,您需要使用重写而不是重定向。
下面是自定义ExceptionMiddleware的简化代码
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILoggerFactory _loggerFactory;
public ExceptionMiddleware(
RequestDelegate next,
ILoggerFactory loggerFactory
)
{
_next = next;
_loggerFactory = loggerFactory;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
var logger = _loggerFactory.CreateLogger("Serilog Global exception logger");
logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
PathString originalPath = context.Request.Path;
context.Request.Path = "/Error";
try
{
var exceptionHandlerFeature = new ExceptionHandlerFeature()
{
Error = ex,
Path = originalPath.Value,
};
context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
context.Features.Set<IExceptionHandlerPathFeature>(exceptionHandlerFeature);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await _next(context);
return;
}
catch (Exception ex2)
{
}
finally
{
context.Request.Path = originalPath;
}
}
}