且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ExceptionFilter 不运行 .NET Core Web Api

更新时间:2023-02-15 12:29:58

我不确定你的例子有什么问题,但我就是这样做的.

I am not sure what is wrong with your example, but this is how I have done it.

首先是异常过滤器:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {

然后我将过滤器添加到整个控制器,而不仅仅是一个动作,尽管这也可能有效——我从未尝试过:

I then add the filter to the whole controller, not just an action, although that might work too--I have never tried it:

[ServiceFilter(typeof(CustomExceptionFilterAttribute))]
public class MyController : ControllerBase
{

并在 Startup.cs、ConfigureServices 中添加 DI 支持:

And in Startup.cs, ConfigureServices, add DI support:

services.AddScoped<CustomExceptionFilterAttribute>();

这个 博客 更详细.