IAsyncActionFilter写日志
1、配置log4net查看
https://www.cnblogs.com/handsomeziff/p/16213689.html
2、创建类CustomAsyncActionFilterAttribute继承Attribute, IAsyncActionFilter

1 using Microsoft.AspNetCore.Mvc.Filters; 2 3 namespace Project6.Utility.Filters 4 { 5 public class CustomAsyncActionFilterAttribute : Attribute, IAsyncActionFilter 6 { 7 private readonly ILogger<CustomAsyncActionFilterAttribute> _logger; 8 9 public CustomAsyncActionFilterAttribute(ILogger<CustomAsyncActionFilterAttribute> logger) 10 { 11 _logger = logger; 12 } 13 public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 14 { 15 var controllerName = context.HttpContext.GetRouteValue("controller"); 16 var actionName = context.HttpContext.GetRouteValue("action"); 17 var para = context.HttpContext.Request.QueryString.Value; 18 _logger.LogInformation($"执行{controllerName} - {actionName}方法:参数为:{para}"); 19 20 //去执行控器里面的Action 21 ActionExecutedContext executedContext = await next.Invoke(); 22 23 var result = Newtonsoft.Json.JsonConvert.SerializeObject(executedContext.Result); 24 _logger.LogInformation($"执行{controllerName} - {actionName}方法:结果为:{result}"); 25 } 26 } 27 }
3、创建控制器CustomAsyncActionFilterController

1 using Microsoft.AspNetCore.Mvc; 2 using Project6.Utility.Filters; 3 4 namespace Project6.Controllers 5 { 6 public class CustomAsyncActionFilterController : Controller 7 { 8 public CustomAsyncActionFilterController() 9 { 10 Console.WriteLine("控制器构造函数"); 11 } 12 13 [TypeFilter(typeof(CustomAsyncActionFilterAttribute))] 14 //[ServiceFilter(typeof(CustomActionFilterAttribute))] 15 public IActionResult Index(int id) 16 { 17 ViewBag.user = Newtonsoft.Json.JsonConvert.SerializeObject(new 18 { 19 Id = id, 20 Name = "ViewBag" 21 }); 22 ViewData["UserInfo"] = Newtonsoft.Json.JsonConvert.SerializeObject(new 23 { 24 Id = id + 1, 25 Name = "ViewData" 26 }); 27 28 object description = "描述信息"; 29 return View(description); 30 } 31 } 32 }
4、在各个方法处设置断点,运行/CustomAsyncActionFilter?id=1
可以发现程序的执行顺序CustomAsyncActionFilterAttribute构造方法-->
CustomAsyncActionFilterController构造方法-->
CustomAsyncActionFilterAttribute.OnActionExecutionAsync方法-->
执行到ActionExecutedContext executedContext = await next.Invoke();跳到控制器的Action方法CustomAsyncActionFilterController.Index-->
控制器Action方法执行完后,继续执行上一步代码之后的内容
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现