首页 > 解决方案 > 如何在 ASP.NET CORE MVC 中使用 IExceptionHandler?

问题描述

我在我的项目中使用 IExceptionHandler 时遇到问题。

我需要安装任何 NuGet 包吗?

当我尝试使用时,Visual Studio 没有找到参考。他问我是否要创建一个名为 IExceptionHandler 的接口。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EventMotors.Controllers
{
    public class ErrorController : Controller
    {
        private readonly IExceptionHandler _exceptionHandler;

        public ErrorController(IExceptionHandler exceptionHandler)
        {
            _exceptionHandler = exceptionHandler;
        }
    }
}

标签: asp.net-coreasp.net-core-mvc

解决方案


IExceptionHandler不在 asp.net 核心中。在错误操作中,您可以使用IExceptionHandlerPathFeature在错误处理程序控制器或页面中访问异常和原始请求路径:

var exceptionHandlerPathFeature =
    HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}

请参考文档:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1


推荐阅读