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

如何通过Swagger配置为所有API端点路由添加accounting-service前缀

统一添加API路由前缀accounting-service的解决方案

针对你的需求,无需逐个修改控制器即可全局添加路由前缀,以下是两种适配不同ASP.NET Core版本的可行方案:

方案一:.NET 6+ 推荐使用路由组(Route Groups)

路由组是.NET 6及以后版本引入的特性,能轻松为一组路由统一添加前缀,同时兼容已有的API版本控制配置:

  1. 在Program.cs(或Startup.cs的Configure方法)的端点配置中,先创建路由组并指定前缀accounting-service,再在组内映射控制器:
app.UseEndpoints(endpoints =>
{
    // 创建全局路由组,添加前缀
    var accountingApiGroup = endpoints.MapGroup("accounting-service");

    // 在组内映射控制器,自动继承前缀并保留原有版本路由规则
    accountingApiGroup.MapControllers();

    // 如果使用API版本约定路由(而非属性路由),可在组内配置完整路由模板
    // accountingApiGroup.MapControllerRoute(
    //     name: "apiVersioned",
    //     pattern: "api/v{version:apiVersion}/{controller}/{action=Index}/{id?}"
    // );
});
  1. 验证Swagger显示:
    Swagger会自动识别路由组前缀,生成的API文档路径会自动带上accounting-service。如果需要保持Swagger UI的访问路径不变,可在配置SwaggerUI时添加:
app.UseSwaggerUI(options =>
{
    options.RoutePrefix = "swagger"; // 自定义Swagger UI的访问路径,可选
    // 其他Swagger配置...
});

方案二:ASP.NET Core 3.1及以下 使用全局路由前缀中间件

如果你的项目基于旧版本框架,可通过自定义中间件实现全局路由前缀:

  1. 创建路由前缀中间件类:
public class RoutePrefixMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _prefix;

    public RoutePrefixMiddleware(RequestDelegate next, string prefix)
    {
        _next = next;
        _prefix = prefix.Trim('/');
    }

    public async Task Invoke(HttpContext context)
    {
        // 检查请求路径是否包含前缀,若包含则截取剩余部分作为实际路由
        if (context.Request.Path.StartsWithSegments($"/{_prefix}", out var remainingPath))
        {
            context.Request.Path = remainingPath;
        }
        await _next(context);
    }
}

// 扩展方法简化中间件注册
public static class RoutePrefixExtensions
{
    public static IApplicationBuilder UseRoutePrefix(this IApplicationBuilder app, string prefix)
    {
        return app.UseMiddleware<RoutePrefixMiddleware>(prefix);
    }
}
  1. 在Startup的Configure方法中注册中间件(需放在UseRouting之后,UseEndpoints之前):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其他中间件配置(如UseStaticFiles、UseAuthentication等)...

    app.UseRouting();

    // 注册全局路由前缀中间件
    app.UseRoutePrefix("accounting-service");

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        // 原有的API版本路由配置保持不变
    });
}

关键注意事项

  • 若使用属性路由(控制器上标注[Route("api/v{version:apiVersion}/[controller]")]),两种方案都会自动将前缀与原有路由模板拼接,无需修改控制器代码。
  • 确保API版本控制的配置(如AddApiVersioning、AddApiExplorer)保持原有逻辑,无需额外调整版本参数的解析规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:05:24