# 記錄http請求 ## 環境 * .net7 ## 一、過濾器(Filter) 這個過程用的的是操作過濾器(`ActionFilter`) ## 二、 ### 2.1 繼承`IAsyncActionFilter` ### 2.2 重寫`OnActionExecutionAsync` `OnAct ...
記錄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);
}
}
}