Sobes.tech
Junior — Middle

What types of Action filters can you name and how are they used?

sobes.tech AI

Answer from AI

In ASP.NET MVC and ASP.NET Core, there are several types of Action filters that allow executing code before and after a controller action:

  • Authorization Filters — check user access rights before executing the action.
  • Action Filters — execute before and after the action method, allowing to modify input parameters or the result.
  • Result Filters — execute before and after the result of the action is formed (for example, before rendering the view).
  • Exception Filters — handle exceptions that occur during the execution of the action.

Example of using an Action Filter for logging the execution time of an action:

public class LogActionFilter : ActionFilterAttribute
{
    private Stopwatch stopwatch;

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        stopwatch = Stopwatch.StartNew();
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        stopwatch.Stop();
        var elapsed = stopwatch.ElapsedMilliseconds;
        // Log the execution time
        Console.WriteLine($"Action executed in {elapsed} ms");
    }
}

// Applying the filter to a controller method
[LogActionFilter]
public IActionResult Index()
{
    // ...
}