Filters in ASP.NET Core

1. Definition of filter

Filter (filter, which can also be translated as "filter") is an aspect programming mechanism provided in ASP.NET Core, which allows developers to create custom filters to deal with cross-cutting concerns, that is, in ASP.NET Core executes our custom code in a specific location, such as the code that executes data inspection before the controller's operation method, or writes custom data into the response header when ActionResult is executed, etc.

There are five types of filters in ASP.NET Core: Authorization Filters, Resource Filters, Operational Filters, Exception Filters, and Result Filters. When developing projects, we generally configure authorization policies or write custom authorization policies instead of writing custom authorization filters. Custom authorization filters are only used when custom authorization frameworks are required. Similar principles apply to resource filters and result filters, so this section focuses on exception filters and action filters.

All filters generally have synchronous and asynchronous versions. For example, synchronous action filters implement the IActionFilter interface, while asynchronous action filters implement the IAsyncActionFilter interface. In most scenarios, asynchronous filters have better performance and can support writing asynchronous call code in the implementation class.

2. Execution order of filters

3. Realization

public class MyExceptionFilter : IAsyncExceptionFilter

{

private readonly ILogger<MyExceptionFilter> logger;

private readonly IHostEnvironment env;

public MyExceptionFilter(ILogger<MyExceptionFilter> logger, IHostEnvironment env)

{

this.logger = logger;

this.env= env;

}

public Task OnExceptionAsync(ExceptionContext context)

{

Exception exception = context.Exception;

logger.LogError(exception,"UnhandledException occured");

string message;

if(env.IsDevelopment())

mespage =exception.tostring();

else

message="The program you appear to handle the exception";

objeckResult result = new ObjectResult (nesw(code=500,massage =message });

result.statusCode = 500;

content Result = result;

centent Excoptionlandled =true;

return Task.CompletedTask;

}}

An asynchronous exception filter should implement the IAsyncExceptionFilter interface. Since the filter needs to record the exception information to the 88 well and judge the execution environment of the program word, the filter needs to inject the two services of ILogger and IHostEnvircament. In the 12th line of code, we use context.Exception to obtain the exception object, and then in the 13th line of code, write the exception into the log. In the 14th to 18th line of code, we detect the operating environment of the program to determine the value of message Whether to display the exception stack prompt Obviously, in the production environment, we cannot display the exception stack to avoid leaking the confidential information of the program. In lines 19~21, we set the content of the response message. In the 22nd line of code, we set the value of contextExceptionHandled to true. In this way, we tell ASPNET Core not to execute the default exception response logic.

Then, we add code before the builder Build of Program.cs to set the global filter.

builder.Services.Configure<MycOptions>(options =>

{

options filters .Add<MyExceptionfiiter>();

});

Guess you like

Origin blog.csdn.net/qq_71012549/article/details/128650047