Advertisement
Intermediate ASP.NET Core, Filters

What is an IResourceFilter, and how does its position in the pipeline (before model binding) make it useful for short-circuiting expensive work?

Short answer

Resource filters run before model binding occurs and after the result has executed, wrapping nearly the entire remaining pipeline -- their early position (before model binding) makes them ideal for short-circuiting a request cheaply (like returning a cached response or rejecting…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Resource filters run before model binding occurs and after the result has executed, wrapping nearly the entire remaining pipeline -- their early position (before model binding) makes them ideal for short-circuiting a request cheaply (like returning a cached response or rejecting based on a header check) before the potentially expensive work of binding and validating a complex request body ever happens.
public class CachedResponseFilter : IResourceFilter {
    public void OnResourceExecuting(ResourceExecutingContext context) {
        var cacheKey = context.HttpContext.Request.Path;
        if (_cache.TryGetValue(cacheKey, out IActionResult cached)) {
            context.Result = cached;  // short-circuits BEFORE model binding even runs
        }
    }
    public void OnResourceExecuted(ResourceExecutedContext context) { }
}
Real-world example
A caching resource filter returns a cached response before the framework even attempts to bind and validate the incoming request body, avoiding wasted binding/validation work for requests that will be served entirely from cache anyway.
Likely follow-ups
  • How does this differ in timing from an action filter, which runs after model binding?
  • What's the trade-off of resource filters versus achieving similar short-circuiting via middleware instead?
Related topics