Advertisement
Beginner ASP.NET Core, Filters

How do you exclude a globally-registered filter from running on one specific action or controller?

Short answer

Implement IFilterFactory-based skip logic or, more simply, use the [OverrideActionFilters] / a marker attribute (like NonAction-style opt-out via IFilterMetadata scanning) or check a condition inside the filter itself (e.g., skipping if a [SkipFilter] marker attribute is present…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Implement IFilterFactory-based skip logic or, more simply, use the [OverrideActionFilters] / a marker attribute (like NonAction-style opt-out via IFilterMetadata scanning) or check a condition inside the filter itself (e.g., skipping if a [SkipFilter] marker attribute is present on the action) -- since the framework does not offer a built-in universal 'exclude this global filter' attribute out of the box, exclusion is usually implemented by having the filter check for an opt-out marker attribute via context.ActionDescriptor.EndpointMetadata.
public class SkipLoggingAttribute : Attribute { }

public class LogActionFilter : IActionFilter {
    public void OnActionExecuting(ActionExecutingContext context) {
        if (context.ActionDescriptor.EndpointMetadata.OfType<SkipLoggingAttribute>().Any()) return;
        Console.WriteLine($"Executing {context.ActionDescriptor.DisplayName}");
    }
    public void OnActionExecuted(ActionExecutedContext context) { }
}

[SkipLogging]
[HttpGet("health")]
public IActionResult Health() => Ok();
Real-world example
A health-check endpoint is excluded from a globally-registered logging filter using a custom SkipLogging marker attribute, preventing log noise from frequent automated health-check polling while every other action remains logged.
Likely follow-ups
  • What's a cleaner alternative if many actions need to be excluded, versus marking each individually?
  • How would you test that the exclusion marker works correctly?
Related topics