today I want to make a short document about filters in .Net Core.
There are by default four types of filters:
- Filters that implement IAuthorizationFilter which allow us to implement OnAuthorization method which allow us to add custom security logic.
- Filters that implement IActionFilter has two methods: OnActionExecuting, OnActionExecuted. Those two methods executed before and after action executing.
- Filters that implement IExceptionFilter has method OnException, which allows to handle exceptions.
- Filters that implement IResultFilter has two methods: OnResultExecuting, OnResultExecuted.
Filters can be applied at controller or at action level. That gives following distinction in their lifetime, if some filter is applied at Controller level, then it will be executed at each action of a controller, which means some filter can make additional workload on your code.
Below goes example of creating filter, which by default generates exception:
public class HasApprovedFilter : Attribute, IAuthorizationFilter
public void OnAuthorization(AuthorizationFilterContext context)
throw new NotImplementedException();
That filter is useless, but take note of class Attribute.
General convention of IAuthorizationFilter is like this: in case if Authorization is correct, then method returns void, if not, we need to set result value on the context object.