What can a filter do? Basically, it allows you to do extra operations (such as permission validation) before and after the action method while reducing the amount of duplicate code and code maintenance.

If you want to use the action filter in the Controller, you can implement this interface:

IActionFilter
Copy the code

Then override the interface methods. Here are some:

void OnActionExecuted(ActionExecutedContext context); Called after the action executes, before the action result. Void OnActionExecuting(ActionExecutingContext context); Called before the action executes, after model binding is complete.Copy the code

The official notes for both methods are very clear and literal.

We know how to use filters, but how does it help us reduce the amount of repetitive code?

Suppose I have 10 actions, and five of them require users to log in before they can access them. If I didn’t use filters, I would have had to validate the user login status with the same code across all five actions. But with filters, I only need to write the code once:

public void OnActionExecuting(ActionExecutingContext context) { var controller = context.Controller.GetType(); string actionname = context.RouteData.Values["action"].ToString(); Bool isNotLoginAttribute = Controller.getMethod (actionName).getCustomAttributes (Typeof (your defined feature class), true).length > 0; if (isNotLoginAttribute) return; Bool isOK = Operation of verifying login permission; if (! IsOK) context.Result = BadRequest(" unauthorized access denied!" ); }Copy the code

You only need to mark the custom feature on the required action(method, controller) to complete login authentication.

In addition to the above, there is another filter that is more commonly used:

IExceptionFilter
Copy the code

Literally, it’s an exception filter. It only has one method

void OnException(ExceptionContext context); Called after an action has thrown an system.exception.(Called when an action triggers an Exception)Copy the code

Override this method and go to startup to register a service:

Services.addmvc (option => {option.filters.Add< writable exception Filters >(); });Copy the code

In this way, global exception capture and unified processing can be achieved.

Filters can be thought of as hooks provided by core that fire automatically if the criteria are met, but you are free to decide what to do with them. This practice is AOP, but not all of it. I don’t have much time today, so I’ll write another AOP article later.