You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 WebAPI中OnActionExecuting(HttpActionContext)方法未触发问题

问题原因及解决办法

你的过滤器无法触发的核心问题是ASP.NET Core Web API和旧版ASP.NET Web API的过滤器体系不兼容,具体问题和修正步骤如下:

1. 错误使用了旧版Web API的命名空间

你当前的过滤器继承自System.Web.Http.Filters.ActionFilterAttribute,这是.NET Framework时代的ASP.NET Web API组件,而你的项目是基于.NET Core的(从Program.cs的WebApplication.CreateBuilder可以看出),两者的过滤器管道完全不互通,所以这个过滤器不会被ASP.NET Core的请求管道识别。

修正后的过滤器代码

替换成ASP.NET Core对应的命名空间和上下文类型:

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

public class MyNoActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (IfDisabledLogic(context))
        {
            // 使用ASP.NET Core的Result类型替代旧版的HttpResponseMessage
            context.Result = new NotFoundResult();
        }
        else
            base.OnActionExecuting(context);
    }

    private bool IfDisabledLogic(ActionExecutingContext context)
    {
        return false;
    }
}

2. 过滤器注册方式错误

ASP.NET Core中,如果是通过特性标记在控制器/方法上的过滤器,不需要用AddScoped注册为服务,直接标记特性即可。你添加的builder.Services.AddScoped(typeof(MyNoActionFilterAttribute))属于多余操作,甚至可能干扰正常执行。

如果需要让过滤器全局生效(所有控制器都应用),可以在AddControllers时配置全局过滤器,无需逐个控制器标记:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(options =>
{
    // 全局注册过滤器
    options.Filters.Add<MyNoActionFilterAttribute>();
});
// 移除原有的 builder.Services.AddScoped(typeof(MyNoActionFilterAttribute));

3. 验证修正

修改后重新启动项目,访问ExampleController的接口,就能触发OnActionExecuting方法的断点了。

内容的提问来源于stack exchange,提问作者Librapulpfiction

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:52:46