我有一个需要自定义标题的操作方法。我发现这段代码向UI添加了自定义标头。
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = "Foo-Header",
@in = "header",
type = "string",
required = true
});
}
}
但是我希望能够在其他可能需要不同的自定义标头名称的方法中使用它。像这样,我可以在其中将自定义标头名称传递给构造函数。
public class CustomHeaderOperationFilter : IOperationFilter
{
private string _headerName;
public CustomHeaderOperationFilter(string headerName)
{
_headerName = headerName;
}
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = _headerName,
type = "string",
@in = "header",
required = true,
});
}
}
我只想将其分配给特定的Action方法,所以我希望可以用这样的属性来装饰action方法:
[SwaggerOperationFilter<CustomHeaderOperationFilter>("custom-header-name")]
但是不幸的是,我只能将过滤器的类型传递给属性。有没有办法做到这一点?
答案 0 :(得分:0)
查看Swashbuckle代码后,我决定创建一个自定义SwaggerCustomHeaderOperationFilterAttribute
public class SwaggerCustomHeaderOperationFilterAttribute : BaseCustomSwaggerOperationFilterAttribute
{
public SwaggerCustomHeaderOperationFilterAttribute(string headerName, string headerDescription, bool isRequired)
{
OperationFilter = new CustomHeaderOperationFilter(headerName, headerDescription, isRequired);
}
}
继承自:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class BaseCustomSwaggerOperationFilterAttribute : Attribute
{
public IOperationFilter OperationFilter { get; protected set; }
}
和自定义ApplyCustomSwaggerOperationFilterAttributes:
public class ApplyCustomSwaggerOperationFilterAttributes : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var attributes = apiDescription.GetControllerAndActionAttributes<BaseCustomSwaggerOperationFilterAttribute>();
foreach (var attribute in attributes)
{
attribute.OperationFilter.Apply(operation, schemaRegistry, apiDescription);
}
}
}
通过这种方式,我可以装饰Action方法
[SwaggerCustomHeaderOperationFilter("header-name", "header-description", true)]