asp.net-core - 如何在 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;
}
}
}
解决方案
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
推荐阅读
- python - 在熊猫中将 20191107 转换为 Ymd 日期
- python - 如何应用 ConvLSTM 层
- reactjs - 引导程序未在 NextJs 中加载
- c# - EF Core 5 是否支持 RowsetSize 之类的东西?
- java - 在 Java 中忽略或删除数据集中某些元素的最佳数据结构是什么?
- python - Python多处理没有给出预期的结果
- c# - .NET Core 3 - 在 Docker 环境中加载静态文件
- c++ - Visual Studio 2017,诊断工具意外失败。输出“Unzulässige Funktion”(无效函数)
- algorithm - 如何找到第 x 个十进制数?
- python - 为什么我的cupy不能正确安装?