You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and derive the FilterAttribute class to use that class as an attribute.
For example, implement IExceptionFilter and the FilterAttribute class to create a custom exception filter. In the same way, implement an IAuthorizatinFilter interface and FilterAttribute class to create a custom authorization filter.
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..
}
}
Alternatively, you can also derive a built-in filter class and override an appropriate method to extend built-in filters' functionality.
Let's create a custom exception filter to log every unhandled exception by deriving the built-in HandleErrorAttribute
class and overriding the OnException
method, as shown below.
class MyErrorHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Log(filterContext.Exception);
base.OnException(filterContext);
}
private void Log(Exception exception)
{
//log exception here..
}
}
You can now apply the MyErrorHandler
attribute at the global level or controller or action method level, the same way we applied an HandleError
attribute.
[MyErrorHandler]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}