Sobes.tech
Junior — Middle

Do you have practical experience using Action Filter in your projects?

sobes.tech AI

Answer from AI

Action Filter in C# (for example, in ASP.NET MVC) is a mechanism that allows executing code before and after a controller action. It is used for cross-cutting concerns such as logging, authorization checks, caching, or modifying the result.

Practical experience with using Action Filters typically includes:

  • Creating custom filters by inheriting from ActionFilterAttribute.
  • Overriding the OnActionExecuting and OnActionExecuted methods to perform logic before and after the action.
  • Applying filters to controllers or individual methods via attributes.

Example of a simple Action Filter:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Log the start of the action execution
        Console.WriteLine($"Action start: {context.ActionDescriptor.DisplayName}");
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        // Log the end of the action
        Console.WriteLine($"Action end: {context.ActionDescriptor.DisplayName}");
    }
}

// Usage:
[LogActionFilter]
public IActionResult Index()
{
    return View();
}

This approach helps centrally manage application behavior without duplicating code in each controller method.