A schema filter lets Swashbuckle postmodify generated OpenAPI schemas for parameters, responses, properties, and complex types. It is useful when ordinary annotations cannot express the required schema metadata. section 11.3.4 section 11.3
A practical custom key/value implementation follows these steps:
- Define a CustomKeyValueAttribute with Key and Value properties; permit use on properties and parameters, and allow multiple applications. section 11.3.4
- Implement ISchemaFilter and inspect MemberInfo or ParameterInfo for the custom attributes, then add each pair to schema extensions. section 11.3.4
- Register the filter with options.SchemaFilter<CustomKeyValueFilter>() in the Swashbuckle configuration. section 11.3.4
- Decorate a property or endpoint parameter, regenerate swagger.json, and inspect the resulting schema or SwaggerUI output. section 11.3.4 section 11.3
Adding custom OpenAPI extensions
Applying [CustomKeyValue("x-test-1", "value 1")] and [CustomKeyValue("x-test-2", "value 2")] to UserName produces both extensions in the LoginDTO property schema. Applying [CustomKeyValue("x-test-3", "value 3")] to a board-game endpoint parameter adds the extension to that parameter schema. section 11.3.4
Listing 11.8 CustomKeyValueFilter
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace MyBGList.Attributes
{
public class CustomKeyValueFilter : ISchemaFilter
{
public void Apply(
OpenApiSchema schema,
SchemaFilterContext context)
{
var caProvider = context.MemberInfo
?? context.ParameterInfo
as IcustomAttributeProvider; #1
var attributes = caProvider?
.GetCustomAttributes(true)
.OfType<CustomKeyValueAttribute>(); #2
if (attributes != null) #3
{
foreach (var attribute in attributes)
{
schema.Extensions.Add(
attribute.Key,
new OpenApiString(attribute.Value)
);
}
}
}
}
}
Use the filter listing to follow the Apply method’s responsibilities: locate attribute providers, retrieve matching annotations, and add their values to the OpenAPI schema. section 11.3.4
