Swashuckle SwaggerDocument对象检索(Swashuckle SwaggerD

2019-10-30 02:23发布

我已经集成ASP .NET核心运行状况检查我的解决方案,我已经使用Swashbuckle招摇。 我认为这将是一个不错的主意,健康检查端点添加到招摇。

我发现这个解决方案在StackOverflow上( 集成健康检查端点插入DOTNET核心招摇(开放API)UI ),但我不明白我怎么chould可以采用这种方法。 我一直试图找到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);
 }

Answer 1:

因为没有人知道答案,我设法通过我自己(在某种程度上)弄明白。

首先,您需要创建将实现一个类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>();
});


文章来源: Swashuckle SwaggerDocument object retrieval