繁体   English   中英

Swagger默认“自定义类的示例值”

[英]Swagger default “Example Value” for custom class

这是一个扩展

用于CQRS的ASP.NET中的Json转换

因此,我们创建了一个类来处理API的可选null-capable参数。

现在我希望swagger doc能够匹配这个类,并希望有一个通用的方法来实现

目前它看起来像这样:

{
  "description": {
    "value": "string",
    "hasValue": true
  }
}

当实际需要的JSON是这样的:

{
  "description": "string"
}

与上一个问题一样,我是所涉及的图书馆的新手并且谷歌搜索没有帮助,因此非常感谢Swagger默认设置的帮助。

所以我自己想出来了 - 以为我会发布答案以防其他人以后再使用它。

此类创建一个过滤文档的操作,将值从内部类型直接复制到外部类型

/// <summary>
/// Sets up the swagger documentation for the optional property
/// </summary>
public static class SwaggerOptionalPropertyFilter
{
    /// <summary>
    /// Get the action that applies the swagger documentation for the optional property
    /// </summary>
    public static Action<SwaggerDocument, HttpRequest> GetFilter()
    {
        return (document, request) =>
        {
            foreach (var kvp in document.Definitions)
            {
                if (!kvp.Key.Contains("OptionalProperty")) continue;

                var val = kvp.Value.Properties.Values.FirstOrDefault();

                if (val == null) continue;

                foreach (var pi in typeof(Schema).GetProperties())
                    pi.SetValue(kvp.Value, pi.GetValue(val, null), null);
            }
        };
    }
}

然后应用它就像更改一样简单:

app.UseSwagger();

至:

app.UseSwagger(c => { c.PreSerializeFilters.Add(SwaggerOptionalPropertyFilter.GetFilter()); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM