Sobes.tech
Middle

What is an Action filter and what functions does it perform?

sobes.tech AI

Answer from AI

Action filters in ASP.NET Core are a specific type of filter that intercepts the execution of a controller action method.

Main functions:

  • Before the action executes: They run code before the controller action method is called (OnActionExecuting).
  • After the action executes: They run code after the controller action method has been called, but before the result is formatted (OnActionExecuted).
  • Modifying the context: They can modify the execution context (ActionExecutingContext) or the post-execution context (ActionExecutedContext), for example, adding data to HttpContext.Items, changing routing, or setting the action result.
  • Exception handling: They do not directly handle exceptions but can be used to set an error result if an exception occurs during OnActionExecuting.

Usage examples:

  • Validating request data before calling the action.
  • Adding headers or modifying the response body.
  • Logging request and response information.
  • Caching action results.
  • Performing authorization and authentication (although specialized Authorization and Authentication filters are more commonly used for this).

Implementation: They are created by inheriting from ActionFilterAttribute or implementing the interfaces IActionFilter (synchronous) or IAsyncActionFilter (asynchronous).

// Example of a simple synchronous Action filter
public class CustomActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Logic before action execution
        Console.WriteLine("Before action execution");
        base.OnActionExecuting(context);
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        // Logic after action execution
        if (context.Exception == null && context.Result is ObjectResult objectResult)
        {
            // Modifying the result if there is no exception and the result is ObjectResult
            Console.WriteLine($"Action result status code: {objectResult.StatusCode}");
        }
        Console.WriteLine("After action execution");
        base.OnActionExecuted(context);
    }
}

They are applied to controllers or individual action methods using attributes:

[CustomActionFilter] // Applying to a controller
public class HomeController : Controller
{
    [HttpGet]
    [CustomActionFilter] // Applying to an action method
    public IActionResult Index()
    {
        return Ok("Hello from Index!");
    }
}