【问题标题】:Swagger default "Example Value" for custom class自定义类的 Swagger 默认“示例值”
【发布时间】:2017-06-20 18:02:14
【问题描述】:

这是一个扩展

Json conversion in ASP.NET for CQRS

由此我们创建了一个类来处理 API 的可选可空参数。

现在我希望 swagger 文档与班级相匹配,并希望有一种通用的方式来做到这一点

目前看起来是这样的:

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

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

{
  "description": "string"
}

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

【问题讨论】:

  • 除此之外,我很确定我现在可以为每个项目使用自定义的 swagger 文档来解决这个问题,但对于有效的调试工具来说,这是很多样板代码。我只是在寻找类似于注释的东西,它告诉 swagger 当这个类出现时默认值应该是什么样子。

标签: c# asp.net json swagger


【解决方案1】:

所以我自己想出了这个 - 我想我会发布答案,以防其他人以后可以使用它。

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

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

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2018-05-24
    • 1970-01-01
    • 2022-10-06
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多