# Filters in .NET: Complete guide to authorization, resource, action, exception, and result filters

> ASP.NET Core filters run in the MVC pipeline after action selection, so authorization, validation, and error handling live in one place, not in every action.

- Author: Pavle Davitkovic
- Published: 2026-08-05
- Updated: 2026-08-25
- Topic: .NET
- Canonical: https://pavle.codes/blog/filters-in-net/

HTTP requests flow through multiple layers before reaching your API endpoint. Middleware intercepts requests and responses at the application level. Its access to routing information depends on where it runs: middleware placed after route matching can read the selected endpoint and route values, but it does not receive MVC-specific controller, action-argument, or model-binding contexts.

Filters intercept requests and responses inside the MVC action invocation pipeline. They expose strongly typed contexts for the selected controller action, bound action arguments, model state, results, and filter-specific short-circuiting. Move MVC-specific cross-cutting logic out of controllers by centralizing it in filters.

## What filters do in .NET

[Filters in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#how-filters-work) run after ASP.NET Core selects the action to execute. Depending on the filter stage, they can access the controller instance, action metadata, route values, model state, bound arguments, and action result. Middleware can access `HttpContext`, endpoint metadata, and route values when ordered appropriately, but not these MVC filter contexts.

## Why filters matter

Filters let you write a cross-cutting concern once and apply it everywhere. Authorization logic lives in one place instead of being scattered across actions, and when you change the filter, the change applies to every registration.

## Filter execution pipeline

Filters run in a predictable order, and that order determines how you use them.

<div style="max-width:520px;margin:32px auto;">
<svg viewBox="0 0 560 716" width="100%" role="img" aria-labelledby="pipe-t pipe-d" style="display:block; height:auto">
  <title id="pipe-t">ASP.NET Core filter execution pipeline</title>
  <desc id="pipe-d">A request passes through routing, then the authorization and resource filters, then model binding, the action filter before and after the controller action, the exception filter if anything throws, the result filter, and finally the response. The five filter stages are highlighted; the other stages are ordinary pipeline steps.</desc>
  <defs>
    <marker id="pipe-arrow" viewBox="0 0 8 8" refX="4" refY="4" markerWidth="6" markerHeight="6" orient="auto">
      <path d="M0 0 L8 4 L0 8 z" fill="var(--faint, #7b8a92)"/>
    </marker>
  </defs>
  <g font-family="var(--font-inter), system-ui, sans-serif" font-size="14">
    <!-- non-filter stages -->
    <g>
      <rect x="110" y="8"   width="340" height="44" rx="8" fill="var(--surface-2, #eef2f1)" stroke="var(--line, #d8e0de)"/>
      <text x="280" y="35" text-anchor="middle" fill="var(--muted, #5c6b72)">HTTP request</text>
      <rect x="110" y="72"  width="340" height="44" rx="8" fill="var(--surface-2, #eef2f1)" stroke="var(--line, #d8e0de)"/>
      <text x="280" y="99" text-anchor="middle" fill="var(--muted, #5c6b72)">Routing</text>
      <rect x="110" y="264" width="340" height="44" rx="8" fill="var(--surface-2, #eef2f1)" stroke="var(--line, #d8e0de)"/>
      <text x="280" y="291" text-anchor="middle" fill="var(--muted, #5c6b72)">Model binding</text>
      <rect x="110" y="392" width="340" height="44" rx="8" fill="var(--surface-2, #eef2f1)" stroke="var(--line, #d8e0de)"/>
      <text x="280" y="419" text-anchor="middle" fill="var(--muted, #5c6b72)">Controller action executes</text>
      <rect x="110" y="648" width="340" height="44" rx="8" fill="var(--surface-2, #eef2f1)" stroke="var(--line, #d8e0de)"/>
      <text x="280" y="675" text-anchor="middle" fill="var(--muted, #5c6b72)">Response sent</text>
    </g>
    <!-- filter stages -->
    <g font-weight="600">
      <rect x="110" y="136" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5"/>
      <text x="280" y="163" text-anchor="middle" fill="var(--accent, #1c8577)">Authorization filter<tspan fill="var(--faint, #7b8a92)" font-weight="400"> · runs first</tspan></text>
      <rect x="110" y="200" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5"/>
      <text x="280" y="227" text-anchor="middle" fill="var(--accent, #1c8577)">Resource filter</text>
      <rect x="110" y="328" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5"/>
      <text x="280" y="355" text-anchor="middle" fill="var(--accent, #1c8577)">Action filter<tspan fill="var(--faint, #7b8a92)" font-weight="400"> · OnActionExecuting</tspan></text>
      <rect x="110" y="456" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5"/>
      <text x="280" y="483" text-anchor="middle" fill="var(--accent, #1c8577)">Action filter<tspan fill="var(--faint, #7b8a92)" font-weight="400"> · OnActionExecuted</tspan></text>
      <rect x="110" y="520" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5" stroke-dasharray="5 4"/>
      <text x="280" y="547" text-anchor="middle" fill="var(--accent, #1c8577)">Exception filter<tspan fill="var(--faint, #7b8a92)" font-weight="400"> · if it throws</tspan></text>
      <rect x="110" y="584" width="340" height="44" rx="8" fill="none" stroke="var(--accent, #1c8577)" stroke-width="1.5"/>
      <text x="280" y="611" text-anchor="middle" fill="var(--accent, #1c8577)">Result filter</text>
    </g>
    <!-- connectors -->
    <g stroke="var(--faint, #7b8a92)" stroke-width="1.5" marker-end="url(#pipe-arrow)">
      <path d="M280 52 v10"/>
      <path d="M280 116 v10"/>
      <path d="M280 180 v10"/>
      <path d="M280 244 v10"/>
      <path d="M280 308 v10"/>
      <path d="M280 372 v10"/>
      <path d="M280 436 v10"/>
      <path d="M280 500 v10"/>
      <path d="M280 564 v10"/>
      <path d="M280 628 v10"/>
    </g>
  </g>
</svg>
</div>

### Filter execution order

Filters execute in a nested sequence. Global filters wrap controller filters, which wrap action filters. Executing filters run in order; after-execution handlers run in reverse.

| Scope | On execution | On completion |
|---|---|---|
| Global | Authorization and validation | Cleanup and logging |
| Controller | Controller-level checks | Controller-level cleanup |
| Action | Action-specific logic | Action-level cleanup |

### Example: nested filter execution

Register filters at all three levels and a single request flows: Global → Controller → Action → execute → Action (reverse) → Controller (reverse) → Global (reverse).

## Six built-in filter types

ASP.NET Core provides six filter types, each at a different pipeline stage.

| Filter type | When it runs | Use it for |
|---|---|---|
| Authorization | Before action (first) | Check user permissions, validate API keys (`IAsyncAuthorizationFilter`) |
| Resource | After auth, before binding | Validate resources, short-circuit (`IAsyncResourceFilter`) |
| Action | After binding, before/after action | Logging, transformation, validation (`IAsyncActionFilter`) |
| Exception | When unhandled exception occurs | Centralized error handling (`IAsyncExceptionFilter`) |
| Result | After action, before serialization | Modify headers, transform response (`IAsyncResultFilter`) |
| Endpoint | Minimal API entry point | Validation, logging (`IEndpointFilter`) |

## Authorization filter

[IAsyncAuthorizationFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncauthorizationfilter) runs first, immediately after routing. If authorization fails, short-circuit the request and prevent all further processing.

Use it to check user permissions, validate API keys, or enforce security policies before the action runs.


```csharp
public sealed class ApiKeyAuthorizationFilter(
    DemoAuditLog auditLog,
    IConfiguration configuration)
    : IAsyncAuthorizationFilter
{
    private const string ApiKeyHeader = "X-Api-Key";

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        var suppliedKey = context.HttpContext.Request.Headers[ApiKeyHeader].ToString();
        var expectedKey = configuration["DemoApiKey"];

        if (string.IsNullOrEmpty(expectedKey) || !KeysMatch(suppliedKey, expectedKey))
        {
            await auditLog.WriteAsync(
                "Authorization rejected the request.",
                context.HttpContext.RequestAborted);

            context.HttpContext.Response.Headers.WWWAuthenticate = "ApiKey";
            context.Result = new UnauthorizedObjectResult(new ProblemDetails
            {
                Status = StatusCodes.Status401Unauthorized,
                Title = "Unauthorized",
                Detail = $"Supply a valid API key in the {ApiKeyHeader} header.",
                Instance = context.HttpContext.Request.Path
            });
            return;
        }

        await auditLog.WriteAsync(
            "Authorization accepted the request.",
            context.HttpContext.RequestAborted);
    }

    private static bool KeysMatch(string supplied, string expected)
    {
        var suppliedBytes = Encoding.UTF8.GetBytes(supplied);
        var expectedBytes = Encoding.UTF8.GetBytes(expected);
        return CryptographicOperations.FixedTimeEquals(suppliedBytes, expectedBytes);
    }
}
```

The filter compares the supplied key against the configuration value using [CryptographicOperations.FixedTimeEquals](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptographicoperations.fixedtimeequals), which prevents timing attacks. On mismatch, return a [ProblemDetails](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails) response and log the failure.

The filter reads `configuration["DemoApiKey"]` straight off `IConfiguration`. See [Configuration in .NET](https://pavle.codes/blog/configuration-in-dotnet-sources-providers-precedence/) for how that value gets there from `appsettings.json`, environment variables, or the command line.

## Resource filter

[IAsyncResourceFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncresourcefilter) runs second, after authorization but before model binding. It's the first chance to access the HTTP context after auth succeeds.

Typical jobs for it are checking that required resources exist, measuring request duration, or caching.

```csharp
public sealed class TimingResourceFilter(DemoAuditLog auditLog) : IAsyncResourceFilter
{
    public async Task OnResourceExecutionAsync(
        ResourceExecutingContext context,
        ResourceExecutionDelegate next)
    {
        var stopwatch = Stopwatch.StartNew();

        context.HttpContext.Response.OnStarting(() =>
        {
            context.HttpContext.Response.Headers["X-Resource-Time-Ms"] =
                stopwatch.ElapsedMilliseconds.ToString();
            return Task.CompletedTask;
        });

        await auditLog.WriteAsync(
            "Resource filter: before the remaining MVC pipeline.",
            context.HttpContext.RequestAborted);

        await next();

        stopwatch.Stop();
        await auditLog.WriteAsync(
            $"Resource filter: after the pipeline ({stopwatch.ElapsedMilliseconds} ms).",
            context.HttpContext.RequestAborted);
    }
}
```

The `OnStarting` callback adds the timing header before the response writes to the network.

## Action filter

[IAsyncActionFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncactionfilter) runs third, after model binding. It accesses the bound model, route data, controller instance, and action metadata.

That makes it the right place for validation that depends on the bound model, transformation of incoming or outgoing data, or action-specific logging.


```csharp
public sealed class ValidateItemActionFilter(DemoAuditLog auditLog) : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        await auditLog.WriteAsync(
            "Action filter: before the controller action.",
            context.HttpContext.RequestAborted);

        var request = context.ActionArguments.Values.OfType<CreateItemRequest>().FirstOrDefault();
        if (request is not null && string.IsNullOrWhiteSpace(request.Name))
        {
            context.Result = new BadRequestObjectResult(new ProblemDetails
            {
                Status = StatusCodes.Status400BadRequest,
                Title = "Validation failed",
                Detail = "Name is required (returned by the action filter).",
                Instance = context.HttpContext.Request.Path
            });
            return;
        }

        var executedContext = await next();

        await auditLog.WriteAsync(
            $"Action filter: after the action; canceled={executedContext.Canceled}.",
            context.HttpContext.RequestAborted);
    }
}
```

Return a `BadRequestObjectResult` without calling `next()` to short-circuit and prevent the action from executing.

## Exception filter

[IAsyncExceptionFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncexceptionfilter) runs when an unhandled exception occurs. It centralizes error handling and transforms exceptions into HTTP responses.

For application-wide error handling, use [middleware with IExceptionHandler](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling#exception-handler-lambda) or the [ProblemDetails pattern](https://pavle.codes/blog/problem-details-dotnet/) instead. Middleware operates at the application level and catches errors filters cannot.

```csharp
public sealed class ApiExceptionFilter(DemoAuditLog auditLog) : IAsyncExceptionFilter
{
    public async Task OnExceptionAsync(ExceptionContext context)
    {
        await auditLog.WriteAsync(
            $"Exception filter handled {context.Exception.GetType().Name}.",
            context.HttpContext.RequestAborted);

        context.Result = new ObjectResult(new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "The demo action failed.",
            Detail = context.Exception.Message,
            Instance = context.HttpContext.Request.Path
        })
        {
            StatusCode = StatusCodes.Status500InternalServerError
        };

        context.ExceptionHandled = true;
    }
}
```

Set `ExceptionHandled = true` to mark the exception as handled and prevent propagation.

## Result filter

[IAsyncResultFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncresultfilter) runs after the action executes and you create the result, before serialization and response. It inspects or modifies response headers and the action result itself.

Use [IAsyncAlwaysRunResultFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iasyncalwaysrunresultfilter) if your filter must run even when a prior filter short-circuits.

This example adds a custom response header before the result is serialized:

```csharp
public sealed class ResponseHeaderResultFilter(DemoAuditLog auditLog) : IAsyncResultFilter
{
    public async Task OnResultExecutionAsync(
        ResultExecutingContext context,
        ResultExecutionDelegate next)
    {
        context.HttpContext.Response.Headers["X-Result-Filter"] = "executed";

        await auditLog.WriteAsync(
            "Result filter: before serializing the action result.",
            context.HttpContext.RequestAborted);

        var executedContext = await next();

        await auditLog.WriteAsync(
            $"Result filter: after the result; canceled={executedContext.Canceled}.",
            context.HttpContext.RequestAborted);
    }
}
```

Add response headers, modify content type, or transform the serialized response.

## Endpoint filter

[IEndpointFilter](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iendpointfilter) is for Minimal APIs. It runs before and after the endpoint and accesses its arguments and result.

Use it with Minimal APIs to validate arguments, log requests, or modify the response. Controllers use action filters instead. For argument validation specifically, .NET 10 also added [built-in Minimal API validation](https://pavle.codes/blog/net-10/#minimal-apis-get-built-in-validation) as an alternative to writing it by hand in a filter.

This example validates that a required `name` parameter is provided:

```csharp
public sealed class RequiredNameEndpointFilter(DemoAuditLog auditLog) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context,
        EndpointFilterDelegate next)
    {
        var name = context.GetArgument<string?>(0);
        if (string.IsNullOrWhiteSpace(name))
        {
            await auditLog.WriteAsync(
                "Endpoint filter rejected an empty name.",
                context.HttpContext.RequestAborted);

            return TypedResults.Problem(new ProblemDetails
            {
                Status = StatusCodes.Status400BadRequest,
                Title = "Validation failed",
                Detail = "Query-string parameter 'name' is required.",
                Instance = context.HttpContext.Request.Path
            });
        }

        await auditLog.WriteAsync(
            "Endpoint filter: before the Minimal API handler.",
            context.HttpContext.RequestAborted);

        var result = await next(context);

        await auditLog.WriteAsync(
            "Endpoint filter: after the Minimal API handler.",
            context.HttpContext.RequestAborted);

        return result;
    }
}
```

## Registering filters


### Global filter registration

Register globally in `Program.cs` to apply to every action:

```csharp
builder.Services.AddControllers(options =>
{
    options.Filters.Add<ApiKeyAuthorizationFilter>();
    options.Filters.Add<ApiExceptionFilter>();
    options.Filters.Add<ResponseHeaderResultFilter>();
});
```

Every request passes through these filters.

Alternatively, use dependency injection:

```csharp
builder.Services.AddControllers(options =>
{
    options.Filters.AddServiceFilter<ApiKeyAuthorizationFilter>();
    options.Filters.AddServiceFilter<ApiExceptionFilter>();
});

builder.Services.AddScoped<ApiKeyAuthorizationFilter>();
builder.Services.AddScoped<ApiExceptionFilter>();
```

### Controller-level filter registration

Apply to all actions in a controller using `[ServiceFilter]` or `[TypeFilter]` on the controller class:

```csharp
[ServiceFilter(typeof(TimingResourceFilter))]
[ServiceFilter(typeof(ValidateItemActionFilter))]
public class ItemsController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreateItem([FromBody] CreateItemRequest request) { }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetItem(int id) { }
}
```

Both actions pass through both filters. Use `[TypeFilter]` to pass constructor parameters not in the dependency container:

```csharp
[TypeFilter(typeof(TimingResourceFilter))]
public class ItemsController : ControllerBase { }
```

### Action-level filter registration

Apply to a single action using `[ServiceFilter]` or `[TypeFilter]` on the method:

```csharp
public class ItemsController : ControllerBase
{
    [HttpPost]
    [ServiceFilter(typeof(ValidateItemActionFilter))]
    public async Task<IActionResult> CreateItem([FromBody] CreateItemRequest request) { }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetItem(int id) { }
}
```

## Filters vs. middleware

[Middleware](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware) and filters both intercept requests, but at different layers. Middleware ordering is configurable: code that runs after route matching can inspect the selected endpoint and route values, and middleware can wrap a broader part of the application than MVC alone. See Microsoft's [routing pipeline guidance](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-10.0#routing-basics).

Filters run inside MVC after action selection and provide stage-specific contexts for authorization, resource handling, bound action arguments, exceptions, and results. Use middleware for application-wide HTTP concerns; use filters when the behavior depends on MVC action semantics.

## Conclusion

Filters handle MVC-specific cross-cutting logic, and you control their scope by registering them globally, per controller, or per action.

Find one piece of repetitive logic in your actions: an auth check, a validation rule, a logging statement. Move it into a filter. Combine filters with middleware and [dependency injection](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection) for clean APIs.
