翼度科技»论坛 编程开发 .net 查看内容

.net 记录http请求

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
记录http请求

环境


  • .net7
一、过滤器(Filter)

这个过程用的的是操作过滤器(ActionFilter)
二、

2.1 继承IAsyncActionFilter

2.2 重写OnActionExecutionAsync

OnActionExecutionAsync - 在调用操作方法前调用
OnActionExecutionAsync(ActionExecutingContext, ActionExecutionDelegate)
ActionExecutingContext 实例化新 ActionExecutingContext 实例,返回关于调用操作方法的信息
ActionExecutionDelegate

  • 异步返回的 ActionExecutedContext 委托,指示已执行操作或下一个操作筛选器
  • 完成后 Task 返回 的 ActionExecutedContext。
三、示例
  1. public class AuditLogActionFilter : IAsyncActionFilter
  2. {
  3.     //AuditLog服务对象,用于保存/查询等操作
  4.     //private readonly IAuditLogService _auditLogService;
  5.     //当前登录用户对象,获取当前用户信息
  6.     // 这些都是Abp中的,使用会报错。还没去看具体实现
  7.     //private readonly IAbpSession _admSession;
  8.     //系统日志接口,用于记录一些系统异常信息
  9.     //private readonly ILogger<AuditActionFilter> _logger;
  10.     //客户端信息接口,获取浏览器,IP等信息
  11.     //private readonly IClientInfoProvider _clientInfoProvider;
  12.     public MysqlDbContext _dbContext;
  13.     public AuditLogActionFilter(MysqlDbContext dbContext)
  14.     {
  15.         _dbContext = dbContext;
  16.     }
  17.     // 方法进去前执行
  18.     public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  19.     {
  20.         //接口Type
  21.         var type = (context.ActionDescriptor as ControllerActionDescriptor).ControllerTypeInfo.AsType();
  22.         //方法信息
  23.         var method = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo;
  24.         //方法参数
  25.         var arguments = context.ActionArguments;
  26.         //开始计时
  27.         var stopwatch = Stopwatch.StartNew();
  28.         var Request = context.HttpContext.Request;
  29.         var Response = context.HttpContext.Response;
  30.         var auditInfoLog = new AuditInfoLog
  31.         {
  32.             Url = Request.Host.Value + Request.Path.Value, // 请求的URL
  33.             Host = Request.Host.Host.ToString(), // 请求地址
  34.             Port = Request.Host.Port, // 请求端口
  35.             Headers = Request.Headers.ToString(), // 请求头
  36.             Method = Request.Method, // 请求方法
  37.             ExcuteStartTime = DateTime.Now, // 执行开始时间
  38.             ServiceName = type != null ? type.FullName : "",
  39.             Parameters = JsonConvert.SerializeObject(arguments), // 请求参数
  40.             StatusCode = Response.StatusCode // 返回状态码
  41.         };
  42.         ActionExecutedContext result = null;
  43.         try
  44.         {
  45.             result = await next();
  46.             if (result.Exception != null && !result.ExceptionHandled)
  47.             {
  48.                 auditInfoLog.Exception = result.Exception.ToString(); // 异常信息
  49.             }
  50.         }
  51.         catch (Exception ex)
  52.         {
  53.             auditInfoLog.Exception = ex.ToString(); // 异常信息
  54.             throw;
  55.         }
  56.         finally
  57.         {
  58.             stopwatch.Stop();
  59.             auditInfoLog.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
  60.             if (result != null)
  61.             {
  62.                 switch (result.Result)
  63.                 {
  64.                     case ObjectResult objectResult:
  65.                         auditInfoLog.ReturnValue = objectResult.Value.ToString();
  66.                         break;
  67.                     case JsonResult jsonResult:
  68.                         auditInfoLog.ReturnValue = jsonResult.Value.ToString();
  69.                         break;
  70.                     case ContentResult contentResult:
  71.                         auditInfoLog.ReturnValue = contentResult.Content;
  72.                         break;
  73.                 }
  74.             }
  75.             Console.WriteLine(auditInfoLog.ToString());
  76.             auditInfoLog.ReturnValue = auditInfoLog.ReturnValue; // 请求返回值
  77.             //保存审计日志
  78.             #region  存储到数据库
  79.             auditInfoLog.ExcuteEndTime = auditInfoLog.ExcuteStartTime.Add(stopwatch.Elapsed);
  80.             await _dbContext.AuditInfoLog.AddAsync(auditInfoLog);
  81.             _dbContext.SaveChanges();
  82.             #endregion
  83.             #region 存储到本地
  84.             var date = DateTime.Now.ToString("yyyy-MM-dd");
  85.             var HttpLogPage = ($"LocalLogs/HttpLogs");
  86.             // 判断是否有这个文件夹,没有则生成
  87.             if (!Directory.Exists(HttpLogPage))
  88.             {
  89.                 Directory.CreateDirectory(HttpLogPage);
  90.             }  
  91.             using (StreamWriter sw = new StreamWriter($"{HttpLogPage}/HttpLog{date}.txt",true))
  92.             {
  93.                 sw.WriteLine($"接口服务名称:   {auditInfoLog.ServiceName}");
  94.                 sw.WriteLine($"请求URL:   {auditInfoLog.Url}");
  95.                 sw.WriteLine($"请求地址:   {auditInfoLog.Host}");
  96.                 sw.WriteLine($"请求端口:   {auditInfoLog.Port}");
  97.                 sw.WriteLine($"请求方法:   {auditInfoLog.Method}");
  98.                 sw.WriteLine($"请求参数:   {auditInfoLog.Parameters}");
  99.                 sw.WriteLine($"返回状态码:   {auditInfoLog.StatusCode}");
  100.                 sw.WriteLine($"返回数据:   {auditInfoLog.ReturnValue}");
  101.                 sw.WriteLine($"执行开始时间:   {auditInfoLog.ExcuteStartTime.ToString("yyyy-MM-dd HH:mm:ss.fffffff")}");
  102.                 sw.WriteLine($"执行时间:   {auditInfoLog.ExecutionDuration}ms");
  103.                 sw.WriteLine($"执行结束时间:   {auditInfoLog.ExcuteEndTime.ToString("yyyy-MM-dd HH:mm:ss.fffffff")}");
  104.                 sw.WriteLine($"异常信息:   {auditInfoLog.Exception}");
  105.                 sw.WriteLine("======================================================");
  106.                 sw.WriteLine();
  107.             }
  108.             #endregion
  109.             //await _auditLogService.SaveAsync(auditInfo);
  110.         }
  111.     }
  112. }
复制代码
来源:https://www.cnblogs.com/zbfoot/archive/2023/08/23/17650579.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具