[英]Swagger default “Example Value” for custom class
這是一個擴展
因此,我們創建了一個類來處理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.