Swashbuckle(Swagger)中的默认模型示例
Default model example in Swashbuckle (Swagger)
我是 运行 ASP WebAPI 2 并成功安装了 Swashbuckle。我想弄清楚如何定义默认架构值是什么?
例如,在 Swagger 现场演示站点上,他们将 pet 的默认值更改为 "doggie"。他们还定义了状态的允许值。 (Live Demo)
我按照这个 link:
上的内容设法使它正常工作
https://github.com/domaindrivendev/Swashbuckle/issues/69#issuecomment-53953785
简而言之,这是需要做的事情:
创建 classes SwaggerDefaultValue 和 AddDefaultValues,如 link 中所述。我所做的一些更改:
public class SwaggerDefaultValue : Attribute
{
public string Name { get; set; }
public string Value { get; set; }
public SwaggerDefaultValue(string value)
{
this.Value = value;
}
public SwaggerDefaultValue(string name, string value) : this(value)
{
this.Name = name;
}
}
public class AddDefaultValues : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
IDictionary<string, object> parameterValuePairs =
GetParameterValuePairs(apiDescription.ActionDescriptor);
foreach (var param in operation.parameters)
{
var parameterValuePair = parameterValuePairs.FirstOrDefault(p => p.Key.IndexOf(param.name, StringComparison.InvariantCultureIgnoreCase) >= 0);
param.@default = parameterValuePair.Value;
}
}
private IDictionary<string, object> GetParameterValuePairs(HttpActionDescriptor actionDescriptor)
{
IDictionary<string, object> parameterValuePairs = new Dictionary<string, object>();
foreach (SwaggerDefaultValue defaultValue in actionDescriptor.GetCustomAttributes<SwaggerDefaultValue>())
{
parameterValuePairs.Add(defaultValue.Name, defaultValue.Value);
}
foreach (var parameter in actionDescriptor.GetParameters())
{
if (!parameter.ParameterType.IsPrimitive)
{
foreach (PropertyInfo property in parameter.ParameterType.GetProperties())
{
var defaultValue = GetDefaultValue(property);
if (defaultValue != null)
{
parameterValuePairs.Add(property.Name, defaultValue);
}
}
}
}
return parameterValuePairs;
}
private static object GetDefaultValue(PropertyInfo property)
{
var customAttribute = property.GetCustomAttributes<SwaggerDefaultValue>().FirstOrDefault();
if (customAttribute != null)
{
return customAttribute.Value;
}
return null;
}
}
编辑您的 SwaggerConfig 并将 AddDefaultValues class 添加到 OperationFilters:
GlobalConfiguration.Configuration
.EnableSwagger(c => {
...
c.OperationFilter<AddDefaultValues>()
...
});
现在对于我想要默认值的参数,我只需添加以下内容:
public IHttpActionResult Put([FromBody]Pet pet)
{
...
return Ok();
}
public class Pet {
[SwaggerDefaultValue("doggie")]
public string Name { get; set; }
[SwaggerDefaultValue("available")]
public string Status;
...
}
好吧,vgaspar.trivix 的代码对我来说并不完全适用,没有为架构设置默认值。我也得到了 NullPointerException
。我设法通过编辑 Apply
方法使其按预期工作,并像这样操作 schemaRegistry:
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
return;
IDictionary<string, object> parameterValuePairs =
GetParameterValuePairs(apiDescription.ActionDescriptor);
foreach (var param in operation.parameters)
{
if (param.schema != null && param.schema.@ref != null)
{
string schemaName = param.schema.@ref.Split('/').LastOrDefault();
if (schemaRegistry.Definitions.ContainsKey(schemaName))
foreach (var props in schemaRegistry.Definitions[schemaName].properties)
{
if (parameterValuePairs.ContainsKey(props.Key))
props.Value.@default = parameterValuePairs[props.Key];
}
}
var parameterValuePair = parameterValuePairs.FirstOrDefault(p => p.Key.IndexOf(param.name, StringComparison.InvariantCultureIgnoreCase) >= 0);
param.@default = parameterValuePair.Value;
}
}
可以通过实施 ISchemaFilter
并使用以下内容注册它来定义示例模型模式:
httpConfig
.EnableSwagger(c =>
{
c.SchemaFilter<AddSchemaExamples>()
});
这里提供了一个示例实现:
public class AddSchemaExamples : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (type == typeof(Product))
{
schema.example = new Product
{
Id = 123,
Type = ProductType.Book,
Description = "Treasure Island",
UnitPrice = 10.0M
};
}
}
}
Source: https://github.com/domaindrivendev/Swashbuckle/issues/162
我知道这个帖子已经很老了,但我想分享我的解决方案,它为 Swagger 示例模式创建了一个自定义构造函数。
在我的模型中:
/// <summary>
/// Supply a custom constructor for Swagger where you can apply defaults to control the example schema.
/// The constructor must have one parameter of type System.Reflection.ParameterInfo[].
/// Note: Setting a property to null will prevent it from showing in the Swagger example.
/// </summary>System.Reflection.ParameterInfo[].
/// </summary>
public class SwaggerConstructor : Attribute { }
在SwaggerConfig.cs中:
c.SchemaFilter<ApplySchemaVendorExtensions>();
架构扩展:
public class ApplySchemaVendorExtensions : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
ConstructorInfo constructor = type.GetConstructors().FirstOrDefault(c => c.GetCustomAttribute<SwaggerConstructor>() != null);
if (constructor != null)
{
schema.example = constructor.Invoke(new object[] { constructor.GetParameters() });
}
}
}
用法:
[SwaggerConstructor]
public MyClass(System.Reflection.ParameterInfo[] decoy) : base()
{
MyProperty = false;
}
刚才偶然发现了这个,你也可以在XML文档中设置标签,在我的一个模型中,我已经定义了这个
/// <summary>
/// Note content
/// </summary>
/// <example>Any text for a note.</example>
public string Note { get; set; }
选择 "Try It Now"
时,在 swagger 文档中最终看起来像这样
希望对某人有所帮助!
将 .NET 5 与 Swashbuckle.AspNetCore 5.6.3 一起使用,我能让它高效工作的唯一方法是:
public class ExampleDocFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
string ToCamelCase(string name) => char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties == null) return;
var setProperties = context.Type.GetProperties().ToList().Where(f => f.GetCustomAttribute<DefaultValueAttribute>() != null).Where(f => schema.Properties.Any(n => n.Key.Equals(ToCamelCase(f.Name)))).ToDictionary(f => f, f => f.GetCustomAttribute<DefaultValueAttribute>());
foreach (var prop in setProperties) schema.Properties[ToCamelCase(prop.Key.Name)].Example = OpenApiAnyFactory.CreateFor(schema.Properties[ToCamelCase(prop.Key.Name)], prop.Value.Value);
}
}
要使用它 - 在您的 startup.cs:
services.AddSwaggerGen(swagger => {
...
swagger.SchemaFilter<ExampleDocFilter>();
});
我是 运行 ASP WebAPI 2 并成功安装了 Swashbuckle。我想弄清楚如何定义默认架构值是什么?
例如,在 Swagger 现场演示站点上,他们将 pet 的默认值更改为 "doggie"。他们还定义了状态的允许值。 (Live Demo)
我按照这个 link:
上的内容设法使它正常工作https://github.com/domaindrivendev/Swashbuckle/issues/69#issuecomment-53953785
简而言之,这是需要做的事情:
创建 classes SwaggerDefaultValue 和 AddDefaultValues,如 link 中所述。我所做的一些更改:
public class SwaggerDefaultValue : Attribute { public string Name { get; set; } public string Value { get; set; } public SwaggerDefaultValue(string value) { this.Value = value; } public SwaggerDefaultValue(string name, string value) : this(value) { this.Name = name; } } public class AddDefaultValues : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { IDictionary<string, object> parameterValuePairs = GetParameterValuePairs(apiDescription.ActionDescriptor); foreach (var param in operation.parameters) { var parameterValuePair = parameterValuePairs.FirstOrDefault(p => p.Key.IndexOf(param.name, StringComparison.InvariantCultureIgnoreCase) >= 0); param.@default = parameterValuePair.Value; } } private IDictionary<string, object> GetParameterValuePairs(HttpActionDescriptor actionDescriptor) { IDictionary<string, object> parameterValuePairs = new Dictionary<string, object>(); foreach (SwaggerDefaultValue defaultValue in actionDescriptor.GetCustomAttributes<SwaggerDefaultValue>()) { parameterValuePairs.Add(defaultValue.Name, defaultValue.Value); } foreach (var parameter in actionDescriptor.GetParameters()) { if (!parameter.ParameterType.IsPrimitive) { foreach (PropertyInfo property in parameter.ParameterType.GetProperties()) { var defaultValue = GetDefaultValue(property); if (defaultValue != null) { parameterValuePairs.Add(property.Name, defaultValue); } } } } return parameterValuePairs; } private static object GetDefaultValue(PropertyInfo property) { var customAttribute = property.GetCustomAttributes<SwaggerDefaultValue>().FirstOrDefault(); if (customAttribute != null) { return customAttribute.Value; } return null; } }
编辑您的 SwaggerConfig 并将 AddDefaultValues class 添加到 OperationFilters:
GlobalConfiguration.Configuration .EnableSwagger(c => { ... c.OperationFilter<AddDefaultValues>() ... });
现在对于我想要默认值的参数,我只需添加以下内容:
public IHttpActionResult Put([FromBody]Pet pet) { ... return Ok(); } public class Pet { [SwaggerDefaultValue("doggie")] public string Name { get; set; } [SwaggerDefaultValue("available")] public string Status; ... }
好吧,vgaspar.trivix 的代码对我来说并不完全适用,没有为架构设置默认值。我也得到了 NullPointerException
。我设法通过编辑 Apply
方法使其按预期工作,并像这样操作 schemaRegistry:
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
return;
IDictionary<string, object> parameterValuePairs =
GetParameterValuePairs(apiDescription.ActionDescriptor);
foreach (var param in operation.parameters)
{
if (param.schema != null && param.schema.@ref != null)
{
string schemaName = param.schema.@ref.Split('/').LastOrDefault();
if (schemaRegistry.Definitions.ContainsKey(schemaName))
foreach (var props in schemaRegistry.Definitions[schemaName].properties)
{
if (parameterValuePairs.ContainsKey(props.Key))
props.Value.@default = parameterValuePairs[props.Key];
}
}
var parameterValuePair = parameterValuePairs.FirstOrDefault(p => p.Key.IndexOf(param.name, StringComparison.InvariantCultureIgnoreCase) >= 0);
param.@default = parameterValuePair.Value;
}
}
可以通过实施 ISchemaFilter
并使用以下内容注册它来定义示例模型模式:
httpConfig
.EnableSwagger(c =>
{
c.SchemaFilter<AddSchemaExamples>()
});
这里提供了一个示例实现:
public class AddSchemaExamples : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (type == typeof(Product))
{
schema.example = new Product
{
Id = 123,
Type = ProductType.Book,
Description = "Treasure Island",
UnitPrice = 10.0M
};
}
}
}
Source: https://github.com/domaindrivendev/Swashbuckle/issues/162
我知道这个帖子已经很老了,但我想分享我的解决方案,它为 Swagger 示例模式创建了一个自定义构造函数。
在我的模型中:
/// <summary>
/// Supply a custom constructor for Swagger where you can apply defaults to control the example schema.
/// The constructor must have one parameter of type System.Reflection.ParameterInfo[].
/// Note: Setting a property to null will prevent it from showing in the Swagger example.
/// </summary>System.Reflection.ParameterInfo[].
/// </summary>
public class SwaggerConstructor : Attribute { }
在SwaggerConfig.cs中:
c.SchemaFilter<ApplySchemaVendorExtensions>();
架构扩展:
public class ApplySchemaVendorExtensions : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
ConstructorInfo constructor = type.GetConstructors().FirstOrDefault(c => c.GetCustomAttribute<SwaggerConstructor>() != null);
if (constructor != null)
{
schema.example = constructor.Invoke(new object[] { constructor.GetParameters() });
}
}
}
用法:
[SwaggerConstructor]
public MyClass(System.Reflection.ParameterInfo[] decoy) : base()
{
MyProperty = false;
}
刚才偶然发现了这个,你也可以在XML文档中设置标签,在我的一个模型中,我已经定义了这个
/// <summary>
/// Note content
/// </summary>
/// <example>Any text for a note.</example>
public string Note { get; set; }
选择 "Try It Now"
时,在 swagger 文档中最终看起来像这样希望对某人有所帮助!
将 .NET 5 与 Swashbuckle.AspNetCore 5.6.3 一起使用,我能让它高效工作的唯一方法是:
public class ExampleDocFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
string ToCamelCase(string name) => char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties == null) return;
var setProperties = context.Type.GetProperties().ToList().Where(f => f.GetCustomAttribute<DefaultValueAttribute>() != null).Where(f => schema.Properties.Any(n => n.Key.Equals(ToCamelCase(f.Name)))).ToDictionary(f => f, f => f.GetCustomAttribute<DefaultValueAttribute>());
foreach (var prop in setProperties) schema.Properties[ToCamelCase(prop.Key.Name)].Example = OpenApiAnyFactory.CreateFor(schema.Properties[ToCamelCase(prop.Key.Name)], prop.Value.Value);
}
}
要使用它 - 在您的 startup.cs:
services.AddSwaggerGen(swagger => {
...
swagger.SchemaFilter<ExampleDocFilter>();
});