【问题标题】:How to customize Swagger endpoint url?如何自定义 Swagger 端点 url?
【发布时间】:2019-04-16 15:17:11
【问题描述】:

我有多个 web api 项目(微服务),我想只使用一个 swagger-ui 链接来公开它们。 为了这篇文章,我将调用每个 Web api 项目 EndpointA 和 EndpointB。

我创建了一个 swagger-ui 项目,并将每个端点添加到该项目中。

我的 swagger-ui 项目Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/EndpointA/swagger/v1/swagger.json", "EndpointA");
        c.SwaggerEndpoint("/EndpointB/swagger/v1/swagger.json", "EndpointB");
    });
}

我的端点 A/B Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "EndpointA", // or "EndpointB",
        });
    });
}

我的问题是每个swagger.json 文件都不包含端点前缀。路径不是/EndpointA/Controller/Action,而是无效的/Controller/Action。


我曾尝试在我的 swagger ui 项目中设置一个自定义 url 前缀,例如 c.RoutePrefix = "EndpointA";。它适用于我的 EndpointA,但我只能为所有端点设置一个,因此 EndpointB 将不起作用。

我也尝试使用SwaggerGen 直接在每个端点中设置前缀,但我不知道如何/如果可能的话。

【问题讨论】:

  • 如果您有两个 Web API 项目,那么大概您正在配置(或可以配置)两个 IApplicationBuilders。您是否尝试过为每个项目显式配置 swagger?换句话说,只需为每个 API 提供一个专用的 Swagger UI。
  • @mclark1129 当然可以,但我的问题是我的所有项目都可以只有一个 swagger-ui 吗?
  • 看这里:swagger-net-test-multiapiversions.azurewebsites.net/swagger/ui/… ...右上角有一个下拉菜单可以选择swagger规范,这是你想做的吗?
  • @HelderSepulveda 是的,就是这样,但使用不同的端点而不是版本。

标签: c# asp.net-core swagger swagger-ui swashbuckle


【解决方案1】:

我最终使用UsePathBaseExtensions.UsePathBase(IApplicationBuilder, PathString) Method 来注册我的 api 的基本路径。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UsePathBase(new PathString("/EndpointA"));
    app.UseMvc();
}

另一种解决方案是使用 swagger 基本路径文档过滤器,如下所示:

public void ConfigureServices(IServiceCollection services)
{
     services.AddSwaggerGen(c =>
     {
         c.DocumentFilter<BasePathFilter>();
     });
 }

还有过滤器:

public class BasePathFilter: IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.BasePath = "/EndpointA";
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2021-02-25
    • 2017-11-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2021-06-01
    相关资源
    最近更新 更多