In ASP.NET Core MVC, how do you write an action filter that records who called each payroll admin action and how long it took?
answer
- IAsyncActionFilter.OnActionExecutionAsync
- await next() returns ActionExecutedContext
- ActionArguments and HttpContext.User
- register with Filters.Add<T>() or an attribute
- set Result without next to short-circuit
basics
~20 sImplement IAsyncActionFilter: record the user and start a Stopwatch, await next() to run the action, then read ActionExecutedContext for the result or exception and write the audit entry. Register it globally with Filters.Add<T>() or per controller with [ServiceFilter].
solid answer
~40 sAn action filter wraps the action after model binding, so it sees the caller (`context.HttpContext.User`), the action (`context.ActionDescriptor.DisplayName`) and the bound `context.ActionArguments`. Implement `IAsyncActionFilter`: do the before work, call `await next()` once, and the returned `ActionExecutedContext` tells you whether the action threw (`Exception`), was short-circuited (`Canceled`) or produced a `Result`. Write the audit entry after that, with the elapsed time. To apply it to every controller, register it with `builder.Services.AddControllers(o => o.Filters.Add<AuditFilter>())`, which also gives it constructor injection; for selected controllers derive from `ActionFilterAttribute` or use `[ServiceFilter]`. Implement either the sync or the async interface, not both, because MVC then calls only the async one. Short-circuit by setting `context.Result` and not calling `next`.
code
csharp · 15 linesbuilder.Services.AddScoped<IAuditLog, SqlAuditLog>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddControllers(o => o.Filters.Add<AuditFilter>());
[ApiController]
[Route("api/admin/payroll")]
public class PayrollAdminController(IPayrollService payroll) : ControllerBase
{
[HttpPost("runs/{runId:int}/approve")]
public async Task<IActionResult> Approve(int runId, CancellationToken ct)
{
await payroll.ApproveRunAsync(runId, ct);
return NoContent();
}
}go deeper
Recall that an action filter runs before and after the action, implements IActionFilter or IAsyncActionFilter, and is registered globally or as an attribute.
Explain next() and ActionExecutedContext, short-circuiting with Result, why only the async method runs when both are implemented, and how registration choice affects DI.
Keep audit filters observing rather than deciding: no swallowed exceptions, no personal data in logs, and an Order that sees requests rejected by earlier filters.
Decide which cross-cutting policies belong in a global filter versus middleware or explicit service calls, and how they are discoverable to new team members.
## The requirement A payroll back office has admin actions that change salaries, approve pay runs and correct tax codes. Compliance wants an audit line for each call: who, which action, which arguments, the outcome and how long it took. Writing that code inside every action is repetitive and easy to forget, so it belongs in an **action filter**, MVC's hook that runs immediately before and after an action method. ## What an action filter can see Action filters run after authorization, resource filters and model binding, so their context is rich: - `context.HttpContext.User`: the authenticated principal. - `context.ActionDescriptor`: the action; cast to `ControllerActionDescriptor` for `ControllerName` and `ActionName`. - `context.ActionArguments`: a dictionary of the **bound** arguments, by parameter name, which a filter may read or replace. - `context.Controller`: the controller instance. - `context.Result`: null until a filter sets it to short-circuit. ## Writing it asynchronously ```csharp public sealed class AuditFilter(IAuditLog audit, TimeProvider clock) : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var started = clock.GetTimestamp(); var executed = await next(); // runs later filters + the action await audit.WriteAsync(new AuditEntry( User: context.HttpContext.User.Identity?.Name ?? "anonymous", Action: context.ActionDescriptor.DisplayName, Arguments: context.ActionArguments.Keys.ToArray(), Failed: executed.Exception is not null && !executed.ExceptionHandled, Elapsed: clock.GetElapsedTime(started))); } } ``` Key points: 1. `next()` returns an `ActionExecutedContext`. An exception thrown by the action does **not** surface from `await next()`; it is captured in `executed.Exception`, and MVC rethrows it later unless a filter sets `ExceptionHandled = true` or clears it. 2. Call `next()` **once**. Not calling it, after setting `context.Result`, is how a filter short-circuits; the action and the later action filters are skipped, and the earlier filters see `Canceled = true`. 3. Keep the filter free of per-request fields: the same instance may serve many requests, depending on how it is registered. ## Sync, async and the attribute base class The synchronous interface `IActionFilter` has `OnActionExecuting` and `OnActionExecuted`. They are enough for logic with no awaits, but auditing to a database is I/O, so the async form is the right one. Implement **one** of the two: when a class implements both, MVC checks for the async interface first and calls only `OnActionExecutionAsync`. `ActionFilterAttribute` is an abstract base that implements both action and result filter interfaces plus `IOrderedFilter`. Its default `OnActionExecutionAsync` calls your `OnActionExecuting`, then `next()` if no result was set, then `OnActionExecuted`. Override either the sync methods or the async one, not both. Because it is an attribute, its constructor cannot take services; see `[ServiceFilter]` and `[TypeFilter]` for that. ## Registering it | Registration | Scope | DI in the constructor | |---|---|---| | `o.Filters.Add<AuditFilter>()` in `AddControllers` | every action of every controller | yes, created like `[TypeFilter]` | | `o.Filters.AddService<AuditFilter>()` | every action | yes, resolved from DI (register the type) | | `[ServiceFilter(typeof(AuditFilter))]` on `PayrollAdminController` | that controller | yes, resolved from DI | | `[Audit]` deriving from `ActionFilterAttribute` | where applied | no | For the back office, a global registration guarded by a marker is a common shape: the filter checks `context.ActionDescriptor.EndpointMetadata` for an `[Audited]` attribute and returns early otherwise, so new admin actions are covered by adding one attribute. ## Testing the filter An action filter is plain C#, so it can be unit-tested without a server. Build an `ActionContext` from a `DefaultHttpContext` (set its `User`), a `RouteData` and an `ActionDescriptor`; wrap it in an `ActionExecutingContext` with an argument dictionary and a fake controller object; and pass a `next` delegate that returns an `ActionExecutedContext`, either clean or with `Exception` set. Assert on what the fake `IAuditLog` received. One integration test through `WebApplicationFactory` then proves the registration really applies the filter to the admin controllers. ## Things an audit filter should not do - **Log entire argument values** without thought: salary and bank details are personal data; record identifiers instead. - **Swallow exceptions**: setting `ExceptionHandled` turns a failure into an empty success. Auditing should observe, not decide. - **Miss model-validation failures**: with `[ApiController]`, the automatic 400 is an action filter at `Order = -2000` that short-circuits before your filter at the default `Order` of 0 runs. If invalid requests must be audited too, give the audit filter a lower `Order` or audit in middleware. Action filters do not apply to Razor Pages handlers, which use page filters, or to Minimal API endpoints, which use endpoint filters.
- How does the filter stop an action from running, for example during a payroll freeze?In `OnActionExecutionAsync`, set `context.Result` to a result such as `new ObjectResult(problem) { StatusCode = 423 }` and return without calling `next()`. The action and later action filters are skipped, earlier filters see `Canceled = true`, and result filters still run on the result you set.
- Why does an exception from the action not throw out of await next()?MVC's invoker catches it and stores it in `ActionExecutedContext.Exception` so every action filter's after code can inspect it. If no filter marks it handled, the invoker rethrows it after the action filters unwind, and exception filters or middleware take over.
An action filter is the supervisor who signs the logbook as each operator starts and finishes a shift: they see who came in and what tools were issued, then wait for the shift to end before writing down the outcome. They do not do the work, and if they never let the operator in, the shift simply does not happen.
- An exception thrown by the action surfaces from await next() inside the filter.
- Implementing both IActionFilter and IAsyncActionFilter makes MVC call both.
- An action filter runs before model binding, so ActionArguments is empty.
- A filter attribute deriving from ActionFilterAttribute can take services in its constructor.
- Calling next() twice is how a filter retries a failed action.