June 27, 2024

JaiHoDevs

filters in ASP.NET Core with examples tutorial

Filters in ASP.NET Core are components that can be executed before or after certain stages in the request processing pipeline. They provide a way to encapsulate cross-cutting concerns such as logging, authentication, authorization, error handling, and more. There are several types of filters available in ASP.NET Core:

  1. Authorization Filters
  2. Resource Filters
  3. Action Filters
  4. Exception Filters
  5. Result Filters

Let's look at each type of filter with examples:

1. Authorization Filters

Authorization filters are executed first in the request processing pipeline. They are used to determine whether a user is authorized to access a resource.

public class CustomAuthorizationFilter : IAuthorizationFilter

{

    public void OnAuthorization(AuthorizationFilterContext context)

    {

        // Custom authorization logic

        if (!context.HttpContext.User.Identity.IsAuthenticated)

        {

            context.Result = new ForbidResult();

        }

    }

}


// Applying the filter globally

public void ConfigureServices(IServiceCollection services)

{

    services.AddControllersWithViews(options =>

    {

        options.Filters.Add<CustomAuthorizationFilter>();

    });

}


2. Resource Filters

Resource filters run after authorization filters and before model binding. They are useful for caching or modifying the result before action execution.

public class CustomResourceFilter : IResourceFilter

{

    public void OnResourceExecuting(ResourceExecutingContext context)

    {

        // Logic before the action executes

    }


    public void OnResourceExecuted(ResourceExecutedContext context)

    {

        // Logic after the action executes

    }

}


// Applying the filter to a specific controller

[ServiceFilter(typeof(CustomResourceFilter))]

public class HomeController : Controller

{

    public IActionResult Index()

    {

        return View();

    }

}

filters in ASP.NET Core with examples tutorial


3. Action Filters

Action filters run before and after the execution of an action method. They are useful for running code before and after an action method is called.

public class CustomActionFilter : IActionFilter

{

    public void OnActionExecuting(ActionExecutingContext context)

    {

        // Logic before the action executes

    }


    public void OnActionExecuted(ActionExecutedContext context)

    {

        // Logic after the action executes

    }

}


// Applying the filter to a specific action

public class HomeController : Controller

{

    [ServiceFilter(typeof(CustomActionFilter))]

    public IActionResult Index()

    {

        return View();

    }

}


4. Exception Filters

Exception filters are executed when an exception is thrown during the processing of an action method. They are useful for error handling and logging.

public class CustomExceptionFilter : IExceptionFilter

{

    public void OnException(ExceptionContext context)

    {

        // Custom error handling logic

        context.Result = new JsonResult(new { error = context.Exception.Message });

        context.ExceptionHandled = true;

    }

}


// Applying the filter globally

public void ConfigureServices(IServiceCollection services)

{

    services.AddControllersWithViews(options =>

    {

        options.Filters.Add<CustomExceptionFilter>();

    });

}


5. Result Filters

Result filters run before and after the execution of an action result. They are useful for modifying the result before it is sent to the client.

public class CustomResultFilter : IResultFilter

{

    public void OnResultExecuting(ResultExecutingContext context)

    {

        // Logic before the result is executed

    }


    public void OnResultExecuted(ResultExecutedContext context)

    {

        // Logic after the result is executed

    }

}


// Applying the filter to a specific controller

[ServiceFilter(typeof(CustomResultFilter))]

public class HomeController : Controller

{

    public IActionResult Index()

    {

        return View();

    }

}


Applying Filters

Filters can be applied globally, to controllers, or to action methods. Here’s how to apply them:

  • Globally: In the ConfigureServices method of Startup.cs.
  • Controller Level: Using the [ServiceFilter] or [TypeFilter] attribute on the controller.
  • Action Method Level: Using the [ServiceFilter] or [TypeFilter] attribute on the action method.

Example of Applying a Filter Globally

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews(options =>
    {
        options.Filters.Add<CustomActionFilter>();
    });
}

Example of Applying a Filter to a Controller

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

Example of Applying a Filter to an Action Method

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

Summary

Filters in ASP.NET Core provide a powerful way to implement cross-cutting concerns in a clean and maintainable way. By understanding and using the different types of filters appropriately, you can ensure that your application remains modular and easy to manage.


Subscribe to get more Posts :