ExceptionFilter

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        #region Identity
        private readonly ILogger<CustomExceptionFilterAttribute> _logger;
        private readonly IModelMetadataProvider _modelMetadataProvider;
        public CustomExceptionFilterAttribute(ILogger
       
         logger , IModelMetadataProvider modelMetadataProvider
       )
        {
            this._modelMetadataProvider = modelMetadataProvider;
            this._logger = logger;
        }
        #endregion
        /// <summary>
        ///An exception occurs, but is not handled
        ///You have to log after the exception
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if(! context.ExceptionHandled) {this._logger.LogError($"{context.HttpContext.Request.RouteValues["controller"]} is Error");
                if (this.IsAjaxRequest(context.HttpContext.Request))//header to see if it is XMLHttpRequest
                {
                    context.Result = new JsonResult(new
                    {
                        Result = false,
                        Msg = context.Exception.Message
                    });// Interrupt - the request ends here, no further Action is required
                }
                else
                {
                    var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                    result.ViewData.Add("Exception", context.Exception);
                    context.Result = result;
                }
                context.ExceptionHandled = true; }}private bool IsAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header); }}Copy the code

ActionFilter

public class CustomActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionFilterAttribute)} OnActionExecuted{this.Order}");
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionFilterAttribute)} OnActionExecuting{this.Order}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionFilterAttribute)} OnResultExecuting{this.Order}");
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionFilterAttribute)} OnResultExecuted{this.Order}"); }}public class CustomControllerFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomControllerFilterAttribute)} OnActionExecuted {this.Order}");
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomControllerFilterAttribute)} OnActionExecuting{this.Order}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomControllerFilterAttribute)} OnResultExecuting{this.Order}");
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomControllerFilterAttribute)} OnResultExecuted{this.Order}"); }}public class CustomGlobalFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomGlobalFilterAttribute)} OnActionExecuted{this.Order}");
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomGlobalFilterAttribute)} OnActionExecuting{this.Order}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomGlobalFilterAttribute)} OnResultExecuting{this.Order}");
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomGlobalFilterAttribute)} OnResultExecuted{this.Order}"); }}public class CustomActionCacheFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            context.HttpContext.Response.Headers.Add("Cache-Control"."public,max-age=6000");
            Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuted{this.Order}");
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuting{this.Order}");
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuting{this.Order}");
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuted{this.Order}"); }}Copy the code

ResourceFilter

public class CustomResourceFilterAttribute : Attribute.IResourceFilter.IFilterMetadata
    {
        private static Dictionary<string.IActionResult> CustomCache = new Dictionary<string, IActionResult>();
        /// <summary>
        ///Happens before any other action
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuting");
            //if there is cache, return cache directly
            string key = context.HttpContext.Request.Path;
            if (CustomCache.ContainsKey(key))
            {
                context.Result = CustomCache[key];// Circuit breaker -- Result is generated, but Result still needs to be converted to Html}}/// <summary>
        ///Occurs after the other action
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuted");
            // This should be cached
            string key = context.HttpContext.Request.Path;
            if(! CustomCache.ContainsKey(key)) { CustomCache.Add(key, context.Result); }}}Copy the code

use

Registered global

services.AddControllersWithViews(
            options =>
            {
                options.Filters.Add<CustomExceptionFilterAttribute>();// Global registration
                options.Filters.Add<CustomGlobalFilterAttribute>();
            });
Copy the code

The first way to use

[ServiceFilter(typeof(CustomExceptionFilterAttribute))]
public IActionResult Index()
{
    return View();
}
Copy the code
 public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped(typeof(CustomExceptionFilterAttribute));// Instead of a new container, you can inject it automatically
}
Copy the code

Second way of use

[TypeFilter(typeof(CustomExceptionFilterAttribute))]
public IActionResult Index()
{
    return View();
}
Copy the code

Third way of use

 /// <summary>
    ///Dependency injection based on complete Filter
    /// </summary>
    public class CustomIOCFilterFactoryAttribute : Attribute.IFilterFactory
    {
        private readonly Type _FilterType = null;

        public CustomIOCFilterFactoryAttribute(Type type)
        {
            this._FilterType = type;
        }
        public bool IsReusable => true;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            //return (IFilterMetadata)serviceProvider.GetService(typeof(CustomExceptionFilterAttribute));

            return (IFilterMetadata)serviceProvider.GetService(this._FilterType); }}Copy the code
[CustomIOCFilterFactoryAttribute(typeof(CustomExceptionFilterAttribute))] /public IActionResult Index()
{
    return View();
}
Copy the code

Execution order

/// <summary>
///Global - controller -Action Order defaults to 0 and can be negative from small to large
 /// </summary>
 /// <returns></returns>
 [CustomActionFilterAttribute(Order = 10)]
 [CustomActionFilterAttribute]
 [CustomActionCacheFilterAttribute(Order = -1)]
 public IActionResult Info()
 {
     Console.WriteLine($"This is {nameof(ThirdController)} Info");

     base.ViewBag.Now = DateTime.Now;
     Thread.Sleep(2000);
     return View();
 }
Copy the code

The Resource filter is returned directly using the cached page

[CustomResourceFilterAttribute]// The variable is cached
 public IActionResult Info()
 {
     Console.WriteLine($"This is {nameof(ThirdController)} Info");

     base.ViewBag.Now = DateTime.Now;
     Thread.Sleep(2000);
     return View();
 }
Copy the code