How to use Filters in ASP.NET Core

By FoxLearn 2/3/2025 8:27:28 AM   72
Filters in ASP.NET Core allow developers to execute code at specific stages in the request processing pipeline. This enables running code either before or after specific phases of the pipeline, such as executing actions, handling authorization, or generating results.

ASP.NET Core MVC comes with several built-in filters that perform tasks like authorization, exception handling, caching, etc. Each filter type is designed to execute at different points in the request pipeline. You can also create your own custom filters to fit specific needs. Let's explore how different types of filters work and how you can implement them in ASP.NET Core MVC.

Action Filters in ASP.NET Core MVC

Action filters are triggered both before and after the execution of an action method. These filters are useful when you want to execute custom code before or after an action method runs. For example, you might want to log information before an action is executed or modify the response afterward.

You can implement custom action filters by implementing the IActionFilter interface. Here’s an example of a basic custom action filter:

public class CustomActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Code executed before the action method runs
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Code executed after the action method runs
    }
}

For asynchronous execution, you can implement the IAsyncActionFilter interface:

public class CustomAsyncActionFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // Code executed before the action method runs
        await next(); // Continue the pipeline
        // Code executed after the action method runs
    }
}

To register the custom filter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(config =>
    {
        config.Filters.Add(new CustomActionFilter());
    });
}

Authorization Filters in ASP.NET Core MVC

Authorization filters are executed at the very beginning of the request pipeline, before any other filters. These filters check if the user has the necessary permissions to access the resource.

Here’s an example of a custom authorization filter:

public class CustomAuthorizationFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // Custom logic for user authorization
    }
}

A more specific example might involve enforcing HTTPS:

public class HttpsOnlyAuthorizationFilter : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (!context.HttpContext.Request.IsHttps)
        {
            context.Result = new ForbidResult(); // Forbid access if not HTTPS
        }
    }
}

You can then apply this filter to a controller or action method:

public class HomeController : Controller
{
    [HttpsOnlyAuthorizationFilter]
    public IActionResult Index()
    {
        return View("Hello");
    }
}

Resource Filters in ASP.NET Core MVC

Resource filters are executed right after authorization filters. These filters are useful for tasks like caching or modifying the request response early in the pipeline.

Here's an example of a resource filter that directly manipulates the response:

public class CustomResourceFilter : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.Result = new ContentResult()
        {
            Content = "This is a custom resource filter."
        };
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        // Additional processing after resource execution
    }
}

Result Filters in ASP.NET Core MVC

Result filters are executed before or after the action results are processed. They allow you to modify the result of an action method, such as changing the view that is rendered.

Here’s how you can implement a custom result filter:

public class CustomResultFilter : Attribute, IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        context.Result = new ViewResult
        {
            ViewName = "CustomView"
        };
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
        // Post-processing after the result is executed
    }
}

You can use this filter in a controller like this:

public class HomeController : Controller
{
    [CustomResultFilter]
    public IActionResult Index()
    {
        return View();
    }
}

Exception Filters in ASP.NET Core MVC

Exception filters allow you to handle any exceptions that occur during the request processing pipeline. You can use exception filters to apply global exception handling policies or to log errors in a consistent manner.

Here’s an example of a custom exception filter:

public class CustomExceptionFilter : Attribute, IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new ViewResult
        {
            StatusCode = (int)HttpStatusCode.InternalServerError,
            ViewName = "Error"
        };
        context.ExceptionHandled = true; // Mark exception as handled
    }
}

This filter can catch unhandled exceptions and show a custom error view.

Filters in ASP.NET Core MVC provide a flexible way to run custom code at various stages of the request processing pipeline, such as before and after action execution, handling authorization, and managing exceptions. You can either use built-in filters or create custom ones tailored to your application’s needs.