我使用的是Swashbuckle.AspNetCore,我想通过XML文档为一个参数显示多个示例。我看到规范允许它(https://swagger.io/docs/specification/adding-examples/),但我似乎不知道如何使用Swashbuckle.AspNetCore来实现它。有可能吗?
我试过以下几种方法
<example>"item 1","item 2"</example> <example>["item 1","item 2"]</example> 发布于 2022-09-29 10:18:58
CodingMytra提供了指向我问题的解决方案的链接(https://link.medium.com/bemAjYabHtb)。
注意,根据https://swagger.io/docs/specification/adding-examples/的规范,只有参数才支持多个示例。
如果出于某些原因(如我),您希望显示模式的示例,那么唯一的方法是在属性的描述中显示它们。下面的示例演示了如何进行此操作。
示例属性基类
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public abstract class SwaggerParameterExampleBaseAttribute : Attribute
{ }名称,值示例属性类
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class SwaggerParameterExampleAttribute : SwaggerParameterExampleBaseAttribute
{
public SwaggerParameterExampleAttribute(string name, string value)
{
Name = name;
Value = value;
}
public SwaggerParameterExampleAttribute(string value)
{
Name = value;
Value = value;
}
public string Name { get; }
public string Value { get; }
}Enum示例属性类
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class SwaggerParameterExamplesFromEnumAttribute : SwaggerParameterExampleBaseAttribute
{
public SwaggerParameterExamplesFromEnumAttribute(Type type)
{
if (!type.IsEnum)
throw new ArgumentException("Must be an Enum", nameof(type));
EnumType = type;
}
public Type EnumType { get; }
}示例过滤器
public class ExampleSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type.IsClass)
{
foreach (var pi in context.Type.GetProperties())
{
var attribs = pi.GetCustomAttributes<SwaggerParameterExampleBaseAttribute>().ToArray();
if (attribs?.Length > 0)
{
var prop = schema.Properties.FirstOrDefault(x => x.Key.Equals(pi.Name, System.StringComparison.OrdinalIgnoreCase));
if (!prop.Equals(default(KeyValuePair<string, OpenApiSchema>)))
{
var list = new List<string>();
list.AddRange(attribs.OfType<SwaggerParameterExampleAttribute>().Select(x => x.Value));
foreach (var attrib in attribs.OfType<SwaggerParameterExamplesFromEnumAttribute>().ToArray())
{
list.AddRange(Enum.GetNames(attrib.EnumType));
}
prop.Value.Example = new Microsoft.OpenApi.Any.OpenApiString(list.First());
if (list.Count > 1)
{
prop.Value.Description += $"\r\n\r\n" +
$"The value can be:\r\n" +
$"- {string.Join("\r\n- ", list)}";
}
}
}
}
}
}
}使用
public class MyClass
{
/// <summary>
/// This is my property
/// </summary>
[SwaggerParameterExample("MyExample1")]
[SwaggerParameterExample("MyExample2")]
[SwaggerParameterExamplesFromEnum(typeof(MyEnum))]
public string MyProperty { get; set; }
}会导致用户界面大摇大摆
MyClass {
MyProperty string
example: MyExample1
This is my property
The value can be:
* MyExample1
* MyExample2
* MyEnumString1
* MyEnumString2
}https://stackoverflow.com/questions/73876526
复制相似问题