Swashuckle SwaggerDocument 对象检索

Swashuckle SwaggerDocument object retrieval

我已经在我的解决方案中集成了 ASP .NET Core HealthChecks,而且我已经在使用 Swashbuckle swagger。我认为将 HealthCheck 端点添加到 swagger 中是个好主意。

我在 Whosebug () 中找到了这个解决方案,但我不明白我应该如何使用这个方法。我试图在启动文件中找到 SwaggerDocument,但我没能找到。

如果知道它是如何工作的人分享他们的想法,那就太好了!谢谢!

我想使用的代码:

public const string HealthCheckEndpoint = "/my/healthCheck/endpoint";

public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
    var pathItem = new PathItem();
    pathItem.Get = new Operation()
    {
        Tags = new[] { "ApiHealth" },
        Produces = new[] { "application/json" }
    };

    var properties = new Dictionary<string, Schema>();
    properties.Add("status", new Schema(){ Type = "string" });
    properties.Add("errors", new Schema(){ Type = "array" });

    var exampleObject = new { status = "Healthy", errors = new List<string>()};

    pathItem.Get.Responses = new Dictionary<string, Response>();
    pathItem.Get.Responses.Add("200", new Response() {
        Description = "OK",
        Schema = new Schema() {
            Properties = properties,
            Example = exampleObject }});

    swaggerDoc.Paths.Add(HealthCheckEndpoint, pathItem);
 }

因为没有人知道答案,所以我设法自己弄明白了(不知何故)。

首先,您需要创建一个 class 来实现 IDocumentFilter 接口。

public class HealthCheckStatusFilter : IDocumentFilter
{

    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        var pathItem = new PathItem();
        pathItem.Get = new Operation()
        {
            Tags = new[] { "ApiHealth" },
            Produces = new[] { "application/json" }
        };

        var properties = new Dictionary<string, Schema>();
        properties.Add("status", new Schema(){ Type = "string" });
        properties.Add("errors", new Schema(){ Type = "array" });

        var exampleObject = new { status = "Healthy", errors = new List<string>()};

        pathItem.Get.Responses = new Dictionary<string, Response>();
        pathItem.Get.Responses.Add("200", new Response() {
            Description = "OK",
            Schema = new Schema() {
                Properties = properties,
                Example = exampleObject }});

        swaggerDoc.Paths.Add(HealthCheckEndpoint, pathItem);
    }
}

然后,在 Startup.cs 文件中,在 ConfugreServices 方法中,您需要添加该文档过滤器。

services.AddSwaggerGen(x =>
{
    x.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
    x.DocumentFilter<HealthCheckStatusFilter>();
});