Asp.Net Core 中的 ExceptionHandlerMiddleware 何时可以将 IExceptionHandlerPathFeature 设为 null

Ily*_*dik 5 c# exception .net-core asp.net-core

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

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!");
        }

        ...
    });
});
Run Code Online (Sandbox Code Playgroud)

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

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

小智 3

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

[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);
}
Run Code Online (Sandbox Code Playgroud)

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