IParameterFilter is a Swashbuckle extension point for customizing query-string parameter descriptions while generating an OpenAPI document. Its Apply method can add information that built-in validation attributes do not provide. section 6.1.4 section 11.3
A practical implementation follows these steps:
- Create a filter class implementing IParameterFilter for each custom validation attribute. section 6.1.4
- Implement Apply(OpenApiParameter parameter, ParameterFilterContext context). section 6.1.4 section 11.3
- Inspect context.ParameterInfo for the relevant attribute, then add an OpenAPI schema extension such as pattern. section 6.1.4
- Register the filter with options.ParameterFilter<TFilter>() inside AddSwaggerGen. section 6.1.4
Board-game sorting parameters
SortOrderFilter finds SortOrderValidatorAttribute and writes a regular-expression pattern such as ^ASC$|^DESC$ to the parameter schema. SortColumnFilter similarly derives allowed property names and adds a pattern for sortColumn. Registering both filters causes SwaggerUI and swagger.json to expose these constraints. section 6.1.4 section 11.3
Listing 6.3 SortOrderFilter
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using MyBGList.Attributes;
namespace MyBGList.Swagger
{
public class SortOrderFilter : IParameterFilter
{
public void Apply(
OpenApiParameter parameter,
ParameterFilterContext context)
{
var attributes = context.ParameterInfo?
.GetCustomAttributes(true)
.OfType<SortOrderValidatorAttribute>(); #1
if (attributes != null)
{
foreach (var attribute in attributes) #2
{
parameter.Schema.Extensions.Add(
"pattern",
new OpenApiString(string.Join("|",
attribute.AllowedValues.Select(v => $"^{v}$")))
);
}
}
}
}
}
Use the SortOrderFilter listing to follow the Apply implementation, attribute lookup, iteration, and schema-extension steps. section 6.1.4
