C/C++教程

IActionFilter记录日志

本文主要是介绍IActionFilter记录日志,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、配置log4net查下以下链接

https://www.cnblogs.com/handsomeziff/p/16213689.html

2、添加类CustomActionFilterAttribute,继承Attribute,IActionFilter

 1 using Microsoft.AspNetCore.Mvc.Filters;
 2 
 3 namespace Project6.Utility.Filters
 4 {
 5     public class CustomActionFilterAttribute : Attribute, IActionFilter
 6     {
 7         private readonly ILogger<CustomActionFilterAttribute> _ILogger;
 8 
 9         public CustomActionFilterAttribute(ILogger<CustomActionFilterAttribute> iLogger)
10         {
11             this._ILogger = iLogger;
12         }
13 
14         /// <summary>
15         /// 在Action之后执行
16         /// </summary>
17         /// <param name="context"></param>
18         public void OnActionExecuted(ActionExecutedContext context)
19         {
20            var result = Newtonsoft.Json.JsonConvert.SerializeObject(context.Result);
21             var controllerName = context.HttpContext.GetRouteValue("controller");
22             var actionName = context.HttpContext.GetRouteValue("action");
23             _ILogger.LogInformation($"执行{controllerName} - {actionName},结果为:{result}");
24         }
25 
26         /// <summary>
27         /// 在Action之前执行
28         /// </summary>
29         /// <param name="context"></param>
30         public void OnActionExecuting(ActionExecutingContext context)
31         {
32             var para = context.HttpContext.Request.QueryString.Value;
33             var controllerName = context.HttpContext.GetRouteValue("controller");
34             var actionName = context.HttpContext.GetRouteValue("action");
35             _ILogger.LogInformation($"执行{controllerName} - {actionName},参数为:{para}");
36         }
37     }
38 }
View Code

3、添加控制器CustomActionFilterController

 1 using Microsoft.AspNetCore.Mvc;
 2 using Project6.Utility.Filters;
 3 
 4 namespace Project6.Controllers
 5 {
 6     public class CustomActionFilterController : Controller
 7     {
 8         [TypeFilter(typeof(CustomActionFilterAttribute))]
 9         //[ServiceFilter(typeof(CustomActionFilterAttribute))]
10         public IActionResult Index(int id)
11         {
12             ViewBag.user = Newtonsoft.Json.JsonConvert.SerializeObject(new
13             {
14                 Id = id,
15                 Name = "ViewBag"
16             });
17             ViewData["UserInfo"] = Newtonsoft.Json.JsonConvert.SerializeObject(new
18             {
19                 Id = id+1,
20                 Name = "ViewData"
21             });
22 
23             object description = "描述信息";
24             return View(description);
25         }
26     }
27 }
View Code

4、在各个方法处设置断点,运行程序CustomActionFilter?id=1

可以发现程序先执行CustomActionFilterAttribute构造函数-->

控制器构造函数-->

OnActionExecuting方法-->

控制器里面的Index方法-->

OnActionExecuted方法

 

所以OnActionExecuting和OnActionExecuted分别是在控制器方法执行前后执行的。可以用于请求前后的日志记录。

 

这篇关于IActionFilter记录日志的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!