我已经设法找到解决方案!
我创建了一个IOperationFilter
基于我的自定义ApiRequired
属性的属性为 POST 和 PUT 方法创建新模式的方法(请参阅原始问题)。
internal class ApplyRequiredAttributeFilter : IOperationFilter
{
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
{
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings ) {
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 ) {
continue;
}
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null ) {
continue;
}
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null ) {
continue;
}
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
{
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
};
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties ) {
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null ) {
// If the model property is required in POST/PUT and current HTTP method is POST/PUT
// Add the property to the new schema's required flags.
if ( attribute.RequiredInPut && apiDescription.HttpMethod.Method.Equals( "PUT" ) ||
attribute.RequiredInPost && apiDescription.HttpMethod.Method.Equals( "POST" ) ) {
newSchema.required.Add( property.Name );
string newSchemaName = $"{schemaName}:{apiDescription.HttpMethod.Method}";
if ( !schemaRegistry.Definitions.ContainsKey( newSchemaName ) ) {
schemaRegistry.Definitions.Add( newSchemaName, newSchema );
}
// Change the current model schema reference to the new schema with the addition required flags.
modelParamater.schema.@ref = $"{schemaPath}:{apiDescription.HttpMethod.Method}";
}
}
}
}
}
}
然后我将过滤器添加到我的 EnableSwagger 调用中。
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
{
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
});
属性的使用方式如下:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
{
get;
set;
}
[ApiRequired( RequiredInPost = true )]
public string UserName
{
get;
set;
}
最后,在文档上,所需的标志看起来像这样。POST 方法参数在左侧,而 PUT 方法参数在右侧: