• C#----使用BaseController添加访问日志


    使用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 } }

      

  • 相关阅读:
    5Hibernate入门----青软S2SH(笔记)
    5Hibernate配置及使用方法----青软S2SH(笔记)
    4Struts2标签库----青软S2SH(笔记)
    3Struts2进阶----青软S2SH(笔记)
    Helvetic Coding Contest 2017 online mirror (teams allowed, unrated) M
    Helvetic Coding Contest 2017 online mirror (teams allowed, unrated) A
    Codeforces Round #418 (Div. 2) D
    Codeforces Round #418 (Div. 2) C
    Codeforces Round #418 (Div. 2) B
    Codeforces Round #418 (Div. 2) A
  • 原文地址:https://www.cnblogs.com/wuyabaibsd/p/10985641.html
Copyright © 2020-2023  润新知