Asp.Net Core Filters
Problem
- An ASP.NET Core Web API has 25 endpoints. 15 of them need a query parameter checked before they run.
- Each of those 15 endpoints performs the check inside its own action method, so the same rule lives in fifteen copies.
- During a change, one copy gets missed. That endpoint now silently skips the check.
One rule, maintained in fifteen places.
Solution
Asp.Net Core Filters
- Write the check once as a resource filter. It runs before model binding and before the action executes.
- Attach it with [ServiceFilter] only to the 15 endpoints that need it.
- A request that fails the check is rejected immediately; the action never runs.
One rule, defined once, enforced everywhere it's attached.
Analogy
An office building has 25 rooms, and 15 of them hold confidential files. Instead of telling the staff in each of those rooms to check visitor passes, the building posts one guard at the corridor those 15 rooms share.
The guard checks the pass once, before a visitor reaches any door. The rooms never see a visitor without a valid pass.
A resource filter is that guard, posted only where the check matters.