【发布时间】:2020-02-20 03:14:08
【问题描述】:
我正在尝试创建自定义异常处理中间件。类似于 -> 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
【问题讨论】:
-
when i do redirect then context.Features.Get() is lost是什么意思,能否告诉您如何重现您的问题以及您希望在错误页面中得到什么? -
我的意思是,当在我的中间件中使用 -> context.Response.Redirect("/ErrorHandling/Error") 时,在 Error Razor 页面模型中重定向 httpCtx.Features.Get
() 之后是空;
标签: asp.net-core asp.net-core-middleware