首页 > 解决方案 > 使用 Swashbuckle Aspnetcore 将 `host`、`basePath` 和 `schemes` 添加到 swagger.json

问题描述

我正在使用官方文档逐步方法来配置 Swagger UI 并在我的 ASP.NET 核心 API 应用程序中生成 Swagger JSON 文件。

开始使用 Swashbuckle 和 ASP.NET Core

如果我查看生成的 swagger.json 文件 - 它缺少三个重要属性hostbasePath并且schemes

请帮助我了解我可以添加哪些代码,以便生成的 swagger.json 将具有以下提到的属性/值。

这是一个理想的 swagger.json -如果我遵循应用程序中的文档代码,请注意缺少的host,basePath和值schemes

{
  "swagger": "2.0",
  "info": {
    "version": "v1",
    "title": "Demo API Title"
  },
  "host": "some-url-that-is-hosted-on-azure.azurewebsites.net",
  "basePath": "/api",
  "schemes": ["https"],
  "paths": {
    "/Account/Test": {
      "post": {
        "tags": [
          "Admin"
        ],
        "summary": "Account test method - POST",
        "operationId": "AccountTest",
        "consumes": [],
        "produces": [
          "text/plain",
          "application/json",
          "text/json"
        ],
        "parameters": [],
        "responses": {
          "200": {
            "description": "Success",
            "schema": {
              "type": "boolean"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "NumberSearchResult": {
      "type": "object",
      "properties": {
        "number": {
          "type": "string"
        },
        "location": {
          "type": "string"
        }
      }
    }
  },
  "securityDefinitions": {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "Authorization. Example: \"Authorization: Bearer {token}\""
    }
  },
  "security": [
    {
      "Bearer": []
    }
  ]
}

标签: c#jsonasp.net-coreswaggerswashbuckle

解决方案


.netcore 的最新版本的 Swashbuckle 有一些变化

如果您希望更改 Swashbuckle 中的请求 URL,可能您在 API 网关后面或将自定义域附加到您的 web 应用程序。做这个。

  1. 创建文档过滤器
public class BasePathDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "hxxt://yoursite" } };
        }
    }
  1. 在您的启动文件中。在services.AddSwaggerGen()方法中添加这样的文档过滤器c.DocumentFilter<BasePathDocumentFilter>();

推荐阅读