Types Of Fliters In Net Core

Types of fliters in .Net Core

Hello everybody,

today I want to make a short document about filters in .Net Core.

There are by default four types of filters:

  1. Filters that implement IAuthorizationFilter which allow us to implement OnAuthorization method which allow us to add custom security logic.
  2. Filters that implement IActionFilter has two methods: OnActionExecuting, OnActionExecuted. Those two methods executed before and after action executing.
  3. Filters that implement IExceptionFilter has method OnException, which allows to handle exceptions.
  4. 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 : AttributeIAuthorizationFilter
{
    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.

No Comments

Add a Comment
Comments are closed