Swashuckle SwaggerDocument object retrieval

2019-09-19 20:09发布

问题:

I've integrated ASP .NET Core HealthChecks in my solution and I'm already using Swashbuckle swagger. I thought it would be a nice idea to add the HealthCheck endpoints to the swagger.

I found this solution in the StackOverflow (Integrating HealthCheck endpoint into swagger (open API) UI on dotnet core), but I can't understand how I chould be using this method. I've tried to find SwaggerDocument in the startup file, but I didn't manage to do that.

It would be nice, if somebody, who knows how it works, shares their thoughts! Thanks!

The code that I'd like to use:

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);
 }

回答1:

As nobody knew the answer, I've managed to figure it out by myself (somehow).

First, you need to create a class that would implement IDocumentFilter interface.

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);
    }
}

And then, in the Startup.cs file, in the ConfugreServices method, you need to add that document filter.

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