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

Jsi*_*inh 5 c# json swagger swashbuckle asp.net-core

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

开始使用Swashbuckle和ASP.NET Core

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

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

这里是一个理想的swagger.json -给予重视的hostbasePath并且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": []
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

小智 19

.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" } };
        }
    }
Run Code Online (Sandbox Code Playgroud)
  1. 在您的启动 file.Inservices.AddSwaggerGen()方法中添加这样的文档过滤器c.DocumentFilter<BasePathDocumentFilter>();


Tse*_*eng 8

您可以实现并注册自己的,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" };
    }
}
Run Code Online (Sandbox Code Playgroud)

然后通过注册

services.AddSwaggerGen(options =>
{
    options.DocumentFilter<MyDocumentFilter>();
});
Run Code Online (Sandbox Code Playgroud)


Fra*_*hes 7

编辑 (09SEP20) 下面是一些适用于 asp.netcore Swashbuckle 库的 4.xx 版的代码片段

将来我可能会再发一篇文章,以防下面的新版本更简单(在撰写本文时,它是 5.xx 版)

示例 appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.Hosting.*": "Information"
    }
  },
  "Swagger": {
    "ApiVersion": "localhost",
    "ApiName": "v1",
    "SwaggerRelativeUrl": "/swagger/v1/swagger.json",
    "Title": "SalesforceLocationApi"
  }
}
Run Code Online (Sandbox Code Playgroud)

示例 C# 代码

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.Hosting.*": "Information"
    }
  },
  "Swagger": {
    "ApiVersion": "localhost",
    "ApiName": "v1",
    "SwaggerRelativeUrl": "/swagger/v1/swagger.json",
    "Title": "SalesforceLocationApi"
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 Swashbuckle.AspNetCore Nuget 版本 4.0.1

我需要根据应用程序的托管位置动态添加主机。

这是我的修复

  1. 我您的 startup.cs 将 IHttpContextAccessor 添加到您的服务

  1. 在您的 swagger 配置中,添加一个 DocFilter,如下所示: 在此处输入图片说明 在此处输入图片说明


Enr*_*ico 5

Swagger/open api 3.0 及更高版本需要服务器对象。请参阅:https : //swagger.io/specification/#server-object

像这样在你的启动中设置它

app.UseSwagger(c =>
{
    c.PreSerializeFilters.Add((swagger, httpReq) =>
    {
        swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } };
    });
});
Run Code Online (Sandbox Code Playgroud)