Action Filter in ASP.NET CORE MVC

An action filter is a piece of logic which is called before executing the Action Method and after the Action Method has executed. Action filters can be applied at the controller level and action method level, on controller level it will apply to all action method within that controller.

Let’s create a Custom ActionFilter with name ‘CustomActionFilter‘ and we are going to inherit with IActionFilter interface and implement OnActionExecuted, OnActionExecuting method, the OnActionExecuting method is invoked first and then OnActionExecuted Method.

Implementation

using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace WebApplication4.Filters
{
    public class CustomActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            throw new NotImplementedException();
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            throw new NotImplementedException();
        }
    }
}

After adding ‘CustomActionFilter‘ Action filter first we are going to implement the OnActionExecuting method in that we are going to check Session which has UserRole Value in it. if the value is null then we will redirect it to an error page and another condition is If Session Value does not contain Admin role still, they will redirect it to an error page.

Next, after implementing OnActionExecuting next we are going to implement the OnActionExecuted method in this method we are going to check after executing action method is there any error if yes then we are going to handle it in OnActionExecuted method.

Code Snippet of CustomActionFilter

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using System;

namespace WebApplication4.Filters
{
    public class CustomActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                context.ExceptionHandled = true;
                context.Result = new RedirectToRouteResult
                   (
                   new RouteValueDictionary(new
                   {
                       action = "Error",
                       controller = "Error"
                   }));
            }     
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            string currentUserRole = Convert.ToString(context.HttpContext.Session.GetString("UserRole"));

            if (!string.IsNullOrEmpty(currentUserRole))
            {
                if (currentUserRole != "Admin")
                {
                    context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Error",
                    controller = "Error"
                }));

                }
                else
                {
                    context.Result = new RedirectToRouteResult
               (
               new RouteValueDictionary(new
               {
                   action = "Error",
                   controller = "Error"
               }));

                }
            }
            else
            {
                context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Error",
                    controller = "Error"
                }));

            }
        }
    }
}

How to Apply Filter on Controller

using System;
using Microsoft.AspNetCore.Mvc;
using WebApplication4.Filters;

namespace WebApplication4.Controllers
{
    [TypeFilter(typeof(CustomActionFilter))]
    public class DefaultController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.