Saturday, April 15, 2023

What is an action filter in ASP.NET Core and how does it work?

An action filter is a type of middleware in ASP.NET Core that is used to execute code before or after an action method is executed. Action filters can be used to modify the request or response, perform authentication or authorization checks, add or remove headers or cookies, or log information about the request or response.

Action filters are applied to action methods in a controller using attributes. For example, the [Authorize] attribute is an action filter that is used to ensure that the user is authenticated before executing the action method. Other common action filters in ASP.NET Core include [AllowAnonymous], [ValidateAntiForgeryToken], [RequireHttps], and [ResponseCache].

Here's an example of how to create a custom action filter in ASP.NET Core:
 

public class LogActionFilter : IActionFilter

{

private readonly ILogger _logger;


public LogActionFilter(ILogger<LogActionFilter> logger)

{

     _logger = logger;

}


public void OnActionExecuting(ActionExecutingContext context)

{

     _logger.LogInformation("Action method {ActionName} is executing.", context.ActionDescriptor.DisplayName);

}


public void OnActionExecuted(ActionExecutedContext context)

{

     _logger.LogInformation("Action method {ActionName} has completed with status code {StatusCode}.",

                             context.ActionDescriptor.DisplayName, context.HttpContext.Response.StatusCode);

}

}

 

In this example, the LogActionFilter class implements the IActionFilter interface, which defines two methods: OnActionExecuting and OnActionExecuted. These methods are called by the ASP.NET Core framework before and after the action method is executed, respectively.

In the OnActionExecuting method, the action filter logs a message indicating that the action method is executing, along with its display name. In the OnActionExecuted method, the action filter logs a message indicating that the action method has completed, along with its display name and the HTTP status code of the response.

To apply this action filter to an action method in a controller, you can add the [ServiceFilter] attribute to the method and specify the type of the action filter: 
 
 

[ServiceFilter(typeof(LogActionFilter))]

public IActionResult Index()

{

return View();

}

 


This will cause the LogActionFilter to be executed before and after the Index action method is executed.

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.