c# - 使用 Swashbuckle Aspnetcore 将 `host`、`basePath` 和 `schemes` 添加到 swagger.json
问题描述
我正在使用官方文档逐步方法来配置 Swagger UI 并在我的 ASP.NET 核心 API 应用程序中生成 Swagger JSON 文件。
开始使用 Swashbuckle 和 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": []
}
]
}
解决方案
.netcore 的最新版本的 Swashbuckle 有一些变化
如果您希望更改 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>();
推荐阅读
- kotlin - kotlin中密封类与密封接口有什么区别
- javascript - d3 鼠标光标/指针变回绘图光标
- laravel - 在 react native 和 laravel 中使用 facebook 登录
- javascript - Material-UI 导入顺序更改样式
- angular - 在另一个对象中显示一个对象的数组的数据
- javascript - 我可以在 XSLT 中创建依赖下拉菜单而不一次加载所有内容吗?
- python - 将数据从 Access 数据库导出到 Python 代码
- jmeter - 如何在jmeter中分配不同时间的负载
- jakarta-ee - 是否有在 Java/JakartaEE 中引入反应式编程结构的建议?
- javascript - Javascript - 获取异步函数外部可用的数据