使用BaseController添加访问日志,其中包括请求头
不说那么多直接上代码(给自己也记一下,下次就可以直接用了)
public class BaseController : Controller { public override void OnActionExecuting(ActionExecutingContext context) {
//获取请求头 if (!context.ActionArguments.Any(m => typeof(RequestViewModel).IsInstanceOfType(m.Value)) || !context.HttpContext.Request.Headers.Keys.Contains("HeadConten") || !context.HttpContext.Request.Headers.Keys.Contains("Client") ) { return; } var vItem = new AuditLogs { Action = context.ActionDescriptor.DisplayName, Path = context.HttpContext.Request.Path, Requset = JsonHelper.SerializeObject(context.ActionArguments), Time = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc), Stopwatch = Stopwatch.StartNew(), HeadConten = context.HttpContext.Request.Headers["HeadConten"], ClientInfo = context.HttpContext.Request.Headers["Client"], Ip = context.HttpContext.Request.Headers["X-Original-For"].FirstOrDefault(),//获取ip }; context.HttpContext.Items["auditlog"] = vItem; } public override void OnActionExecuted(ActionExecutedContext context) { var vLog = Request.HttpContext.RequestServices.GetService(typeof(ILoggerService)) as ILoggerService; if (vLog == null) return; if (!(context.HttpContext.Items["auditlog"] is AuditLogs item)) return; var vDuration = item.Stopwatch.ElapsedMilliseconds; var vResult = context.Result as ObjectResult; item.Duration = vDuration; item.Response = JsonHelper.SerializeObject(vResult?.Value); item.Exception = context.Exception; vLog.WriteApiLog(item);//写入mongo } }