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

如何修改ASP.NET Core Swagger中API控制器的显示分组名称

解决ASP.NET Core 7 Swagger v2页面控制器分组名显示问题

方法一:直接给控制器指定ApiExplorer分组名

这是最直接的处理方式,在PatientAppV2Controller上添加[ApiExplorerSettings]特性,明确指定分组名为PatientApp:

[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/PatientApp")]
[ApiExplorerSettings(GroupName = "PatientApp")] // 强制指定分组名
public class PatientAppV2Controller : ControllerBase
{
    // 你的接口方法逻辑
}

方法二:全局配置ApiExplorer分组规则

如果有多个同类型版本控制器需要统一处理,可以在Program.cs中配置ApiExplorer的分组选择逻辑,自动修正分组名:

builder.Services.AddControllers()
    .AddApiExplorer(options =>
    {
        options.ApiVersionParameterSource = new UrlSegmentApiVersionReader();
        // 自定义分组选择逻辑
        options.GroupNameSelector = description =>
        {
            var controllerName = description.ActionDescriptor.RouteValues["controller"];
            // 匹配以PatientAppV开头的控制器,统一返回PatientApp作为分组名
            if (controllerName?.StartsWith("PatientAppV") == true)
            {
                return "PatientApp";
            }
            return controllerName;
        };
    });

方法三:配置Swagger的Tag分组规则

在Swagger生成配置里,通过TagActionsBy方法自定义接口的Tag(即Swagger页面显示的分组名):

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API名称", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "你的API名称", Version = "v2" });

    c.TagActionsBy(api =>
    {
        var controllerActionDescriptor = api.ActionDescriptor as ControllerActionDescriptor;
        if (controllerActionDescriptor == null)
        {
            return new[] { "默认分组" };
        }

        var controllerName = controllerActionDescriptor.ControllerName;
        // 针对PatientAppV2控制器替换分组名
        return controllerName == "PatientAppV2" 
            ? new[] { "PatientApp" } 
            : new[] { controllerName };
    });
});

以上三种方法任选其一都能解决Swagger v2页面中控制器分组名显示为PatientAppV的问题,推荐用方法一快速解决单个控制器的情况,方法二或三适合批量处理多个版本控制器的场景。

内容的提问来源于stack exchange,提问作者Bob.at.Indigo.Health

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:07:46