How to create a custom filter in ASP.NET MVC?

How to create a custom filter in ASP.NET MVC?

In this article, We are going to discuss how to create and use a Custom Filter in ASP.NET MVC Application.

Implement an appropriate filter interface for which you want to create a custom filter and derive the FilterAttribute class to utilize that class as an attribute to generate custom filter attributes.

As the example, Create a custom exception filter by implementing IExceptionFilter and the FilterAttribute class. Create a custom authorization filter by implementing an IAuthorizatinFilter interface and a FilterAttribute class.

class MyErrorHandler : FilterAttribute, IExceptionFilter
{
    public override void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..
 
    }
}

To enhance the functionality of built-in filters, you can derive a built-in filter class and override an appropriate method.

By deriving the built-in HandleErrorAttribute class and overriding the OnException method, we can create a custom exception filter that logs every unhandled exception, as seen below.

class MyErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..
 
    }
}

The MyErrorHandler attribute can now be applied at the global, controller, or action method level, just as the HandleError attribute.

[MyErrorHandler]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

}

Related – How do you fix “Could not load file or assembly or one of its dependencies”

Comments (1)


  1. How To Create C# ASP.NET Core Web Application – storuwa.lk

    […] Previous – How to create a custom filter in ASP.NET MVC? […]

leave your comment

Your email address will not be published.

Top