我正在使用官方文档逐步方法来配置 Swagger UI 并在我的 ASP.NET 核心 API 应用程序中生成 Swagger JSON 文件。
Get started with Swashbuckle and ASP.NET Core
如果我查看生成的 swagger.json 文件 - 它缺少三个重要属性 host
、basePath
和 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": []
}
]
}
最佳答案
最新版本的 Swashbuckle for .netcore 有一些变化
如果您希望在 Swashbuckle 中更改请求 URL,可能您在 API 网关后面或者您的 web 应用程序附加了自定义域。这样做。
- 创建文档过滤器
public class BasePathDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "hxxt://yoursite" } }; } }
- 在您的启动文件中。在
services.AddSwaggerGen()
中方法像这样添加文档过滤器c.DocumentFilter<BasePathDocumentFilter>();
关于c# - 使用 Swashbuckle Aspnetcore 将 `host` 、 `basePath` 和 `schemes` 添加到 swagger.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53793847/