使用Swashbuckle Aspnetcore将`host`,`basePath`和`schemes`添加到swagger.json

问题描述 投票:2回答:1

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

Get started with Swashbuckle and ASP.NET Core

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

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

这是一个理想的swagger.json - 如果我按照我的应用程序中的文档代码注意hostbasePathschemes

{
  "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# json asp.net-core swagger swashbuckle
1个回答
4
投票

您可以实现并注册自己的IDocumentFilter并在那里设置所需的值。

public class MyDocumentFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    {
        swaggerDoc.Host = "some-url-that-is-hosted-on-azure.azurewebsites.net";
        swaggerDoc.BasePath = "/api";
        swaggerDoc.Schemes = new List<string> { "https" };
    }
}

然后通过注册

services.AddSwaggerGen(options =>
{
    options.DocumentFilter<MyDocumentFilter>();
});
© www.soinside.com 2019 - 2024. All rights reserved.