简体   繁体   English

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

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

This is an extension of 这是一个扩展

Json conversion in ASP.NET for CQRS 用于CQRS的ASP.NET中的Json转换

Whereby we created a class to handle optional null-able parameters for our API. 因此,我们创建了一个类来处理API的可选null-capable参数。

Now I want the swagger doc to match up for the class, and was hoping for a generic way to do so 现在我希望swagger doc能够匹配这个类,并希望有一个通用的方法来实现

Currently it looks like this: 目前它看起来像这样:

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

when the actual required JSON is this: 当实际需要的JSON是这样的:

{
  "description": "string"
}

As in the previous question, I'm new to the libraries involved and Googling hasn't helped, so help with the Swagger defaults is muchly appreciated. 与上一个问题一样,我是所涉及的图书馆的新手并且谷歌搜索没有帮助,因此非常感谢Swagger默认设置的帮助。

So I figured this out on my own - thought I'd post the answer in case someone else can use it later. 所以我自己想出来了 - 以为我会发布答案以防其他人以后再使用它。

This class creates an action that filters the documentation, copying the values from the inner type directly to the outer type 此类创建一个过滤文档的操作,将值从内部类型直接复制到外部类型

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

Then applying it is as simple as changing: 然后应用它就像更改一样简单:

app.UseSwagger();

To: 至:

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

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

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