zoukankan      html  css  js  c++  java
  • MVC拦截器之Action拦截器 记录执行时间及日志

    /// <summary>
        /// action拦截器
        /// </summary>
        public class ActionFillters : IActionFilter
        {
            private static readonly Logger _log = LogManager.GetCurrentClassLogger();
            private const string _stopWatchKey = "_stopWatchKey";
    
            /// <summary>
            /// 执行action前执行这个方法
            /// </summary>
            /// <param name="context"></param>
            public void OnActionExecuting(ActionExecutingContext context)
            {
                //定义计时器
                var stopWatch = new Stopwatch();
                context.HttpContext.Items[_stopWatchKey] = stopWatch;
                stopWatch.Start();
                
                //记录日志
                string msg = "执行Action前:" + "请求地址:" + context.HttpContext.Request.Path;
                _log.Info(msg);
            }
            /// <summary>
            /// 执行action后执行这个方法 
            /// </summary>
            /// <param name="context"></param>
            public void OnActionExecuted(ActionExecutedContext context)
            {
                var stopWatch = context.HttpContext.Items[_stopWatchKey] as Stopwatch;
                if (stopWatch != null)
                {
                    stopWatch.Stop();
                    string msg = "执行Action后:" + "请求地址:" + context.HttpContext.Request.Path + " 耗时:" + stopWatch.ElapsedMilliseconds + "毫秒”;
                    _log.Info(msg);
                }
                else
                {
                    string msg = "执行Action后:" + "请求地址:" + context.HttpContext.Request.Path;
                    _log.Info(msg);
                }
            }
        }
    重点:拦截器、HttpContext.Items
  • 相关阅读:
    处理跨浏览器的事件处理程序
    html5 canvas时钟
    拖拽事件的原理
    改变top使用轮播图
    程序开发之最大子数组
    第四周学习进度
    敏捷开发相关阅读
    构建之法读书笔记04
    四则运算终结版
    第三周学习进度
  • 原文地址:https://www.cnblogs.com/jianghaidong/p/12604809.html
Copyright © 2011-2022 走看看