- A+
所属分类:.NET技术
记录http请求
环境
- .net7
一、过滤器(Filter)
这个过程用的的是操作过滤器(ActionFilter
)
二、
2.1 继承IAsyncActionFilter
2.2 重写OnActionExecutionAsync
OnActionExecutionAsync
- 在调用操作方法前调用
OnActionExecutionAsync(ActionExecutingContext, ActionExecutionDelegate)
ActionExecutingContext
实例化新 ActionExecutingContext 实例,返回关于调用操作方法的信息
ActionExecutionDelegate
- 异步返回的 ActionExecutedContext 委托,指示已执行操作或下一个操作筛选器
- 完成后 Task 返回 的 ActionExecutedContext。
三、示例
public class AuditLogActionFilter : IAsyncActionFilter { //AuditLog服务对象,用于保存/查询等操作 //private readonly IAuditLogService _auditLogService; //当前登录用户对象,获取当前用户信息 // 这些都是Abp中的,使用会报错。还没去看具体实现 //private readonly IAbpSession _admSession; //系统日志接口,用于记录一些系统异常信息 //private readonly ILogger<AuditActionFilter> _logger; //客户端信息接口,获取浏览器,IP等信息 //private readonly IClientInfoProvider _clientInfoProvider; public MysqlDbContext _dbContext; public AuditLogActionFilter(MysqlDbContext dbContext) { _dbContext = dbContext; } // 方法进去前执行 public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //接口Type var type = (context.ActionDescriptor as ControllerActionDescriptor).ControllerTypeInfo.AsType(); //方法信息 var method = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo; //方法参数 var arguments = context.ActionArguments; //开始计时 var stopwatch = Stopwatch.StartNew(); var Request = context.HttpContext.Request; var Response = context.HttpContext.Response; var auditInfoLog = new AuditInfoLog { Url = Request.Host.Value + Request.Path.Value, // 请求的URL Host = Request.Host.Host.ToString(), // 请求地址 Port = Request.Host.Port, // 请求端口 Headers = Request.Headers.ToString(), // 请求头 Method = Request.Method, // 请求方法 ExcuteStartTime = DateTime.Now, // 执行开始时间 ServiceName = type != null ? type.FullName : "", Parameters = JsonConvert.SerializeObject(arguments), // 请求参数 StatusCode = Response.StatusCode // 返回状态码 }; ActionExecutedContext result = null; try { result = await next(); if (result.Exception != null && !result.ExceptionHandled) { auditInfoLog.Exception = result.Exception.ToString(); // 异常信息 } } catch (Exception ex) { auditInfoLog.Exception = ex.ToString(); // 异常信息 throw; } finally { stopwatch.Stop(); auditInfoLog.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds); if (result != null) { switch (result.Result) { case ObjectResult objectResult: auditInfoLog.ReturnValue = objectResult.Value.ToString(); break; case JsonResult jsonResult: auditInfoLog.ReturnValue = jsonResult.Value.ToString(); break; case ContentResult contentResult: auditInfoLog.ReturnValue = contentResult.Content; break; } } Console.WriteLine(auditInfoLog.ToString()); auditInfoLog.ReturnValue = auditInfoLog.ReturnValue; // 请求返回值 //保存审计日志 #region 存储到数据库 auditInfoLog.ExcuteEndTime = auditInfoLog.ExcuteStartTime.Add(stopwatch.Elapsed); await _dbContext.AuditInfoLog.AddAsync(auditInfoLog); _dbContext.SaveChanges(); #endregion #region 存储到本地 var date = DateTime.Now.ToString("yyyy-MM-dd"); var HttpLogPage = ($"LocalLogs/HttpLogs"); // 判断是否有这个文件夹,没有则生成 if (!Directory.Exists(HttpLogPage)) { Directory.CreateDirectory(HttpLogPage); } using (StreamWriter sw = new StreamWriter($"{HttpLogPage}/HttpLog{date}.txt",true)) { sw.WriteLine($"接口服务名称: {auditInfoLog.ServiceName}"); sw.WriteLine($"请求URL: {auditInfoLog.Url}"); sw.WriteLine($"请求地址: {auditInfoLog.Host}"); sw.WriteLine($"请求端口: {auditInfoLog.Port}"); sw.WriteLine($"请求方法: {auditInfoLog.Method}"); sw.WriteLine($"请求参数: {auditInfoLog.Parameters}"); sw.WriteLine($"返回状态码: {auditInfoLog.StatusCode}"); sw.WriteLine($"返回数据: {auditInfoLog.ReturnValue}"); sw.WriteLine($"执行开始时间: {auditInfoLog.ExcuteStartTime.ToString("yyyy-MM-dd HH:mm:ss.fffffff")}"); sw.WriteLine($"执行时间: {auditInfoLog.ExecutionDuration}ms"); sw.WriteLine($"执行结束时间: {auditInfoLog.ExcuteEndTime.ToString("yyyy-MM-dd HH:mm:ss.fffffff")}"); sw.WriteLine($"异常信息: {auditInfoLog.Exception}"); sw.WriteLine("======================================================"); sw.WriteLine(); } #endregion //await _auditLogService.SaveAsync(auditInfo); } } }