ASP.NET Core TypeFilter 使用記錄
阿新 • • 發佈:2020-08-20
[HttpGet]
[TypeFilter(typeof(LogActionFilter),Arguments =new object[] { "測試表", "YJYK", "Log_Users", "Insert" , "logCode","我測試一下Aop操作日誌" })]
public IActionResult TestMothod2()
{
return Ok();
}
public class LogActionFilter : Attribute, IActionFilter { private readonly ILogger<LogActionFilter> _logger; private readonly ILog_UsersService _log; public LogActionFilter( ILogger<LogActionFilter> logger, ILog_UsersService log, string tableName = "", string moduleName = "", string methodName = "", string logType = "", string logCode = "", string logDetail = "") { _logger = logger; _log = log; TableName = tableName; ModuleName = moduleName; MethodName = methodName; LogType = logType; LogCode = logCode; LogDetail = logDetail; } public string TableName { get; set; } public string ModuleName { get; set; } /// <summary> /// 方法名 /// </summary> public string MethodName { get; set; } public string LogType { get; set; } /// <summary> /// 日誌返回碼 /// </summary> public string LogCode { get; set; } /// <summary> /// 日誌描述 /// </summary> public string LogDetail { get; set; } public void OnActionExecuted(ActionExecutedContext context) { var logModel = new Model() { LogDetail = LogDetail, Url = context.HttpContext.Request.Path, MethodName = MethodName, LogCode = LogCode, LogType = LogType, TableName = TableName, ModuleName = ModuleName }; try { _log.AddLogAsync(logModel); } catch (Exception ex) { _logger.LogError(ex, "操作日誌異常"); } } public void OnActionExecuting(ActionExecutingContext context) { } }
通過這種方式就實現了 使用注入服務的 過濾器來記錄操作日誌