【问题标题】:How to set base path property in swagger for .Net Core Web API如何在 .Net Core Web API 的 swagger 中设置基本路径属性
【发布时间】:2018-01-01 18:51:55
【问题描述】:

我在 ASP.Net Core(1.1.2 版)中构建了一个 Web API,并使用 Swashbuckle.AspNetCore 来生成 swagger 定义。

下面是自动生成的swagger定义的一部分。我想更改路径,使其不包含 /api/ApiName,但它会包含在 basePath 中,现在是 /

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/api/ApiName",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

所以我想得到的是:

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/",
    "paths": {
        "/api/ApiName": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

我们还有一些其他 API 不是用 .Net Core 编写的,它通过添加默认路由解决了同样的问题。我试图通过删除 API 控制器顶部的路由在 .Net 核心上做同样的事情

[Route("api/[Controller]")]

并将其添加到 Startup.cs。然而这并没有奏效。有人知道如何解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

    BasePath 用于Swagger v2.0 已经被OpenApi v3.0中的servers数组替换了

    在 v5 中,您必须这样做才能使用 OpenApi v3.0:

    var basePath = "/v1";
    app.UseSwagger(c =>
        {
            c.RouteTemplate = "swagger/{documentName}/swagger.json";
            c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
            {
                swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
            });
        });
    

    【讨论】:

      【解决方案2】:

      最后我用这个来修复它:

      您可以设置 PreSerializeFilters 来添加 BasePath 和编辑路径。认为会有更优雅的方式,但这是可行的。

      var basepath = "/api/AppStatus";
      c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = basepath);
      
      
      c.PreSerializeFilters.Add((swaggerDoc, httpReq) => {
          IDictionary<string, PathItem> paths = new Dictionary<string, PathItem>();
          foreach (var path in swaggerDoc.Paths)
          {
              paths.Add(path.Key.Replace(basepath, "/"), path.Value);
          }
          swaggerDoc.Paths = paths;
      });
      

      【讨论】:

        【解决方案3】:

        使用 IDocumentFilter 可以修改结果大摇大摆的定义。
        我有一些例子:

        https://github.com/heldersepu/SwashbuckleTest/blob/master/Swagger_Test/App_Start/SwaggerConfig.cs#L285

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多