This article mainly introduces the ActionFilter filter of asp.net core MVC filter in detail, which has certain reference value. Interested friends can refer to it
This series of classes will Explaining the use of built-in filters in asp.net core MVC will be divided into the following chapters
asp.net core MVC filter ExceptionFilter filter (1)
asp.net core MVC Filter's ActionFilter filter (2)
asp.net core MVC filter's ResultFilter filter (3)
asp.net core MVC filter's ResourceFilter filter (4)
asp.net core MVC filter AuthorizationFilter filter (5)
Introduction
The Action filter will be executed before and after the controller's Action Execute the corresponding method.
Implementing a custom Action filter
Customizing a global exception filter requires implementing the IActionFilter interface
##
public class ActionFilter : IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine("action执行之后"); } public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine("action执行之前"); } }
[HttpGet] public ActionResult Get() { if (!ModelState.IsValid) return BadRequest("参数错误!"); }
public void OnActionExecuting(ActionExecutingContext context) { if (context.ModelState.IsValid) return; var modelState = context.ModelState.FirstOrDefault(f => f.Value.Errors.Any()); string errorMsg = modelState.Value.Errors.First().ErrorMessage; throw new AppException(errorMsg); }
public class ActionFilter : IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { var httpContext = context.HttpContext; var stopwach = httpContext.Items[Resources.StopwachKey] as Stopwatch; stopwach.Stop(); var time = stopwach.Elapsed; if (time.TotalSeconds > 5) { var factory = context.HttpContext.RequestServices.GetService<ILoggerFactory>(); var logger = factory.CreateLogger<ActionExecutedContext>(); logger.LogWarning($"{context.ActionDescriptor.DisplayName}执行耗时:{time.ToString()}"); } } public void OnActionExecuting(ActionExecutingContext context) { var stopwach = new Stopwatch(); stopwach.Start(); context.HttpContext.Items.Add(Resources.StopwachKey, stopwach); } }
Register global filter
The registration method is the same as ExceptionFinter. Find the Startup.cs file in the system root directory and modify the ConfigureServices method as followsservices.AddMvc(options => { options.Filters.Add<ActionFilter>(); });
The above is the detailed content of asp.net ActionFilter filter. For more information, please follow other related articles on the PHP Chinese website!