c# - 使用 Swashbuckle Aspnetcore 将 `host` 、 `basePath` 和 `schemes` 添加到 swagger.json

标签 c# json asp.net-core swagger swashbuckle

我正在使用官方文档逐步方法来配置 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": []
    }
  ]
}

最佳答案

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

如果您希望在 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>();

关于c# - 使用 Swashbuckle Aspnetcore 将 `host` 、 `basePath` 和 `schemes` 添加到 swagger.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53793847/

相关文章:

android - 在 AsyncTask 类中哪里更好地解析 json 字符串?

c# - 在 vnext 应用程序中测试 IActionResult 内容

html - asp.net core 将模型传递给布局

c# - C# 新手,无法创建多维数组

javascript - 单击链接时更改变量

c# - 使用 Visual Studio 2010 创建新的 C# 类时如何定义默认代码

c# - 在 C# 中查找可用的内存插槽

jquery - 如何使用 jquery 将多个 json 格式的参数传递给 Web 服务?

从 web 服务获取数据的 PHP 函数

c# - ENC1003 C# 在应用程序运行时不会应用在项目中所做的更改