Lesson 5 of 8
Filters - Action, Result, Exception & Authorization
Filters run at specific points in the controller action pipeline - before/after model binding, before/after action execution, and on exceptions. They're a cleaner alternative to middleware for controller-specific cross-cutting concerns: idempotency, response shaping, transaction scoping.
Action Filters & Exception Filters
using Microsoft.AspNetCore.Mvc.Filters;
// ━━ IActionFilter - wraps action execution ━━
// Use for: request/response transformation, logging, idempotency
public class IdempotencyFilter(IDistributedCache cache) : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
// Get idempotency key from header
if (!context.HttpContext.Request.Headers
.TryGetValue("X-Idempotency-Key", out var key))
{
await next(); // no key - proceed normally
return;
}
var cacheKey = $"idempotency:{key}";
// Check if we've already processed this request
var cached = await cache.GetStringAsync(cacheKey);
if (cached is not null)
{
context.Result = new ContentResult
{
Content = cached,
ContentType = "application/json",
StatusCode = 200
};
return; // short-circuit - return cached response
}
// Execute the action
var executed = await next();
// Cache the response for 24 hours
if (executed.Result is OkObjectResult { Value: not null } ok)
{
var json = System.Text.Json.JsonSerializer.Serialize(ok.Value);
await cache.SetStringAsync(cacheKey, json,
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24) });
}
}
}
// ━━ IResultFilter - wraps result execution (modifies response) ━━
public class EnvelopeResultFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
// Wrap successful responses in an envelope
if (context.Result is ObjectResult { StatusCode: >= 200 and < 300 } objectResult)
{
context.Result = new OkObjectResult(new
{
success = true,
data = objectResult.Value,
timestamp = DateTime.UtcNow,
requestId = context.HttpContext.Items["CorrelationId"]
});
}
}
public void OnResultExecuted(ResultExecutedContext context) { }
}
// ━━ IExceptionFilter - handle controller exceptions ━━
// Prefer GlobalExceptionHandler (Module 3) - this is for controller-specific exceptions
public class ValidationExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is not FluentValidation.ValidationException ex) return;
context.Result = new UnprocessableEntityObjectResult(new ValidationProblemDetails
{
Status = 422,
Title = "Validation Failed",
Errors = ex.Errors
.GroupBy(e => e.PropertyName)
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())
});
context.ExceptionHandled = true;
}
}
// ━━ Registration ━━
// Global - applies to all controllers:
builder.Services.AddControllers(options =>
{
options.Filters.Add<IdempotencyFilter>();
options.Filters.Add<ValidationExceptionFilter>();
});
// Local - specific controller/action:
[ServiceFilter(typeof(IdempotencyFilter))] // DI-injected filter
[HttpPost]
public IActionResult Create() => Ok();
interface IDistributedCache { Task<string?> GetStringAsync(string key); Task SetStringAsync(string key, string value, DistributedCacheEntryOptions options); }
class DistributedCacheEntryOptions { public TimeSpan? AbsoluteExpirationRelativeToNow { get; set; } }Tip
Tip
Practice Filters Action Result Exception Authorization in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Filters Action Result Exception Authorization from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Filters Action Result Exception Authorization is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?