【问题标题】:Swashuckle SwaggerDocument object retrievalSwashuckle SwaggerDocument 对象检索
【发布时间】:2020-01-09 21:53:17
【问题描述】:

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

我在 StackOverflow (Integrating HealthCheck endpoint into swagger (open API) UI on dotnet core) 中找到了这个解决方案,但我不明白我应该如何使用这个方法。我试图在启动文件中找到 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);
 }

【问题讨论】:

标签: c# asp.net-core .net-core swashbuckle


【解决方案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>();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多