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
原文地址:https://www.cnblogs.com/jianghaidong/p/12604809.html