wasAsked.

MVC Filters

EPAM · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

Filters in ASP.NET Core MVC (and Web API controllers) run code before or after specific stages of the action execution pipeline, for cross-cutting concerns such as authorization, logging, caching, validation and error handling. Filter types in execution order 1. Authorization filters (IAuthorizationFilter, IAsyncAuthorizationFilter): run first; decide whether the request is authorised ([Authorize] is implemented this way). Can short-circuit the request. 2. Resource filters (IResourceFilter): run before model binding and after the rest of the pipeline; useful for caching or short-circuiting expensive work. 3. Action filters (IActionFilter, IAsyncActionFilter): run immediately before and after the action method; can inspect or change arguments and results. Good for validation, logging and timing. 4. Exception filters (IExceptionFilter): handle unhandled exceptions thrown by actions or other filters, converting them into responses. 5. Result filters (IResultFilter): run before and after the action result executes (for example, adding headers or wrapping responses). In addition, endpoint filters (IEndpointFilter) apply to minimal APIs. Example — action filter for timing and validation public sealed class TimingFilter(ILogger<TimingFilter> log) : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext ctx, ActionExecutionDelegate next) { if (!ctx.ModelState.IsValid) { ctx.Result = new BadRequestObjectResult(ctx.ModelState); return; } var sw = Stopwatch.StartNew(); var executed = await next(); log.LogInformation("{Action} took {Ms} ms", ctx.ActionDescriptor.DisplayName, sw.ElapsedMilliseconds); } } Ways to apply filters - Globally: builder.Services.AddControllers(o => o.Filters.Add<TimingFilter>()); - Per controller or action as attributes: [ServiceFilter(typeof(TimingFilter))] (resolves from DI), [TypeFilter(typeof(TimingFilter))], or custom attributes deriving from ActionFilterAttribute. - Order can be controlled with the Order property; scope order is global, then controller, then action (reversed on the way out). Built-in examples: [Authorize], [AllowAnonymous], [ResponseCache], [ApiController]'s automatic model validation, [ProducesResponseType] metadata, and [ValidateAntiForgeryToken]. Filters vs middleware - Middleware runs for every request in the application pipeline and does not know about MVC concepts. - Filters run only for MVC actions and have access to the action context: arguments, model state and results. Use middleware for application-wide concerns (exception handling, CORS, compression) and filters for action-specific behaviour.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics