在 swagger 中支持 asp.net core 可选路由参数

场景

  • 同一个 Controller 可能对不同环境有不同的行为,通过路由的 env 参数调整注入的参数

  • 每一次请求上下文可能会根据 env 的值修改 repo 的具体参数

  • 系统会提供默认的 env, 因此此处的路由参数为可选参数

  • swagger 根据 OpenApi v3.x 规范,即使使用 ? 标注为可选,ui 中仍然为 required

    C# 复制代码
    [Route("api/{env:env?}/[controller]")]
    [ApiController]
    public class DemoController(IDemoRepo repo) : ControllerBase
    {
        /* other codes */
    }

解决方法

  • 增加自定的方法修改已经生成的 swagger 文档
C# 复制代码
builder.Services.AddSwaggerGen(opt =>
{
   opt.OperationFilter<ApplyOptionalRouteParameterOperationFilter>();
   /* other codes */
}

public partial class ApplyOptionalRouteParameterOperationFilter : IOperationFilter
{
   public void Apply(OpenApiOperation operation, OperationFilterContext context)
   {
       if (operation.Parameters.Count == 0) return;
       // 获取方法以及类上面的 RouteAttribute
       var attrs = context.MethodInfo.GetCustomAttributes(true)
           .Concat(context.MethodInfo.DeclaringType?.GetCustomAttributes(true) ?? [])
           .OfType<RouteAttribute>().Where(x => x.Template.Contains('?')).ToList();
           
       // 遍历所有 RouteAttribute,如果包含可选参数,则对应修改 OpenAPI 参数定义
       foreach (var route in attrs)
       {
           var matches = RouteTemplateRegex().Matches(route.Template);
           foreach (Match match in matches)
           {
               var name = match.Groups["name"].Value;
               var parameter = operation.Parameters.FirstOrDefault(x => x.Name == name);
               if (parameter is not null)
               {
                   parameter.AllowEmptyValue = true;
                   parameter.Required = false;
                   parameter.Schema.Nullable = true;
               }
           }
       }
   }

   [GeneratedRegex(@"\{(?<name>\w+)(\:\w+)*\?\}")]
   private static partial Regex RouteTemplateRegex();
}
相关推荐
65岁退休Coder1 小时前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境1 小时前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
码流怪侠1 小时前
用 WiFi 信号数人头:howmanypeoplearearound 项目深度解析
后端·开源·github
心运软件2 小时前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
Jodie同志2 小时前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent
Jodie同志2 小时前
第1~15天:原生Agent、RAG与LangGraph基础(完整代码实操)
前端·后端·agent
Zane19942 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端
用户69371750013842 小时前
#DeepSeek+Pi‑Agent 王炸组合跑赢 Claude‑Code!
前端·人工智能·后端
Zane19942 小时前
类变量与实例变量:一个共享列表引发的线上事故
后端·python