繁体   English   中英

什么时候可以在 Asp.Net Core 中使用 ExceptionHandlerMiddleware 将 IExceptionHandlerPathFeature 设为 null

[英]When can IExceptionHandlerPathFeature be null with ExceptionHandlerMiddleware in Asp.Net Core

Microsoft 在此处ExceptionHandlerMiddleware提供了此示例。 这是摘录:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        ...

        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
        {
            await context.Response.WriteAsync("File error thrown!");
        }

        ...
    });
});

我不太明白他们为什么要使用?. 运算符获取异常? 可以在没有IExceptionHandlerPathFeature情况下触发此委托吗? 在没有保证访问异常的情况下拥有异常处理程序似乎不合逻辑。

是代码,其中似乎不可能有 null 。

在我的特定情况下,我有一个带有以下操作之一的自定义错误控制器:

[Route("Error")]
public IActionResult Error(ErrorViewModel model)
{
    var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    model.Code = 500;

    _logger.Error($"The path {exceptionDetails?.Path} threw an exception " +
         $"{exceptionDetails?.Error}");

    return View(nameof(Error), model);
}

每当用户手动在浏览器中输入我的错误页面路由时, IExceptionHandlerPathFeature为 null。 所以我不得不放空条件运算符来限制空引用异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM