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

如何全局为所有控制器添加ApiExplorerSettings(IgnoreApi=true)属性?

全局添加ApiExplorerSettingsAttribute的解决方案

你推测的没错,ApiExplorerSettingsAttribute是特性类而非过滤器,所以不能通过options.Filters.Add<T>的方式全局注册。这里提供两种可行的全局配置方法:

方法一:自定义控制器约定(推荐)

通过实现IControllerModelConvention接口,给所有控制器统一添加该特性:

  1. 定义约定类
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc;

public class GlobalApiExplorerSettingsConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        // 为所有控制器添加忽略API的设置
        controller.Filters.Add(new ApiExplorerSettingsAttribute { IgnoreApi = true });
    }
}
  1. 注册约定到MVC配置
builder.Services.AddControllers(options =>
{
    options.Conventions.Add(new GlobalApiExplorerSettingsConvention());
});

方法二:利用自定义过滤器间接实现

如果更倾向于过滤器模式,可以自定义一个过滤器,在其中设置ApiExplorer的忽略规则:

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

public class GlobalApiExplorerIgnoreFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        var apiExplorerSettings = context.ActionDescriptor.EndpointMetadata
            .OfType<ApiExplorerSettingsAttribute>()
            .FirstOrDefault();

        // 仅当没有局部设置时,应用全局忽略规则
        if (apiExplorerSettings == null)
        {
            context.ActionDescriptor.EndpointMetadata.Add(
                new ApiExplorerSettingsAttribute { IgnoreApi = true }
            );
        }
    }

    public void OnActionExecuted(ActionExecutedContext context) { }
}

注册过滤器:

builder.Services.AddControllers(options =>
{
    options.Filters.Add<GlobalApiExplorerIgnoreFilter>();
});

后续启用单个控制器

无论用哪种方法,需要暴露API的控制器只需添加局部特性覆盖全局设置即可:

[ApiExplorerSettings(IgnoreApi = false)]
public class PublicController : ControllerBase
{
    // 控制器逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:33:14