A filter pipeline provides a place to change framework behavior without rewriting every action. Two different pipelines matter here: ASP.NET Core filters affect HTTP request processing, while Swashbuckle filters change the generated swagger.json document. Choose the pipeline that owns the behavior you need to change. section 6.2.3 section 11.3
Keep automatic validation except for one action
Suppose a board-game API action needs to handle invalid query input itself, but other actions should retain [ApiController] automatic validation. Implement an attribute using IActionModelConvention. Its Apply method finds and removes that action’s ModelStateInvalidFilter; placing the attribute on the chosen action leaves application-wide automatic validation enabled. The implementation also checks the filter factory by its class name because that type is internal—a fragile detail if the framework changes the name. section 6.2.3
Listing 6.7 ManualValidationFilterAttribute
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace MyBGList.Attributes
{
public class ManualValidationFilterAttribute
: Attribute, IActionModelConvention
{
public void Apply(ActionModel action)
{
for (var i = 0; i < action.Filters.Count; i++)
{
if (action.Filters[i] is ModelStateInvalidFilter
|| action.Filters[i].GetType().Name ==
"ModelStateInvalidFilterFactory")
{
action.Filters.RemoveAt(i);
break;
}
}
}
}
}
The attribute searches the action’s filter collection and removes the automatic model-state validation filter. section 6.2.3
For documentation instead, implement a Swashbuckle filter’s Apply method and register the filter with AddSwaggerGen. Filter interfaces target different parts of swagger.json: the document, operations, query parameters, request bodies, or schemas. For example, IParameterFilter can detect custom sorting validators and add allowed-value patterns to matching parameters. Check the generated JSON to confirm the patterns appear; this changes the documentation and Swagger UI, not the action’s validation logic. section 6.1.4 section 11.3
