我有一个 swagger 定义,并且使用 XML 注释来描述请求和响应并提供有意义的示例。示例模型如下:
/// <summary>Created item information.</summary>
public class ItemCreated
{
/// <summary>Outcome of the item being created.</summary>
/// <value>The outcome.</value>
/// <example>Item has been Created</example>
public string Outcome { get; set; }
/// <summary>Unique item reference.</summary>
/// <value>The Item reference.</value>
/// <example>6001002982178</example>
public string Reference { get; set; }
/// <summary>The external reference for the package.</summary>
/// <value>The carrier reference.</value>
/// <example>5558702516</example>
public string ExternalReference { get; set; }
/// <summary>The items documents.</summary>
/// <value>The items documentation.</value>
/// <example>???</example>
public List<Documentation> Documents { get; set; }
}
/// <summary>Item documentation information.</summary>
[JsonObject("Documentation")]
public class Documentation
{
/// <summary>The document in base64 format.</summary>
/// <value>The document base64 string.</value>
/// <example>JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwM...</example>
[JsonProperty("Document")]
public string Document { get; set; }
/// <summary>The type of the document.</summary>
/// <value>The documentation type.</value>
/// <example>ITEMDOCUMENT_SLIP1</example>
public DocumentationType Type { get; set; }
/// <summary>Document format.</summary>
/// <value>The format of the document.</value>
/// <example>Pdf</example>
public string Format { get; set; }
/// <summary>The document resource uri.</summary>
/// <value>The link to the document resource.</value>
public string Link { get; set; }
}
Swagger 显示为:
我需要的是展示一个更复杂的响应示例。您可以在此处看到其中一个属性是一个数组 - 我想显示多个文档类型 - 因此多个数组项。我该如何展示这个? “”节点不允许数组中存在多个示例。
感谢您提前提供的任何积分!
最佳答案
实现此目的的一种方法是使用架构过滤器:
[SwaggerSchemaFilter(typeof(ItemCreatedSchemaFilter))
public class ItemCreated
{
⋮
}
public class ItemCreatedSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Type == typeof(ItemCreated))
{
schema.Example = new OpenApiObject
{
// Other Properties
["Documents"] = new OpenApiArray
{
new OpenApiObject
{
// Other Properties
["Document"] = new OpenApiString("JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwM..."),
["Format"] = new OpenApiString("Pdf")
},
new OpenApiObject
{
// Other Properties
["Document"] = new OpenApiString("Something else"),
["Format"] = new OpenApiString("Something else")
}
}
};
}
}
}
引用:Apply Schema Filters to Specific Types
记住将新过滤器添加到 SwaggerGen 选项中:
services.AddSwaggerGen(c =>
{
c.SchemaFilter<ItemCreatedFilter>();
...
}
关于c# - Swagger - 如何显示更复杂的响应示例 - ASP.net Core Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61964949/