如何使用ActionFilterAttribute记录运行时间?

zaf*_*s.m 3 c# asp.net-mvc logging action-filter asp.net-web-api

我创建了一个动作过滤器,用于测量Web API v2中每个操作的运行时间.

public class RunningTimeAttribute : ActionFilterAttribute
    {
        private readonly ILogFactory _logFactory;
        private readonly ITimerFactory _timerFactory;
        private ITimer _timer;
        private ILogger _logger;

        public RunningTimeAttribute(ILogFactory logFactory, ITimerFactory timerFactory) {
            if(logFactory == null)
                throw new ArgumentNullException("logFactory");
            if(timerFactory == null)
                throw new ArgumentNullException("timerFactory");

            _logFactory = logFactory;
            _timerFactory = timerFactory;
        }

        public override void OnActionExecuting(HttpActionContext actionContext) {
            base.OnActionExecuting(actionContext);
            OnBeforeAction(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
            OnAfterAction(actionExecutedContext);
            base.OnActionExecuted(actionExecutedContext);
        }

        private void OnBeforeAction(HttpActionContext actionContext) {
            var controllerName = actionContext.ControllerContext.Controller.GetType().FullName;
            var actionName = actionContext.ActionDescriptor.ActionName;

            _logger = _logFactory.Create(controllerName);
            _logger.Trace("Action \"{0}\" begins execution", actionName);

            _timer = _timerFactory.Create();
            _timer.Start();
        }

        private void OnAfterAction(HttpActionExecutedContext actionExecutedContext) {
            var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;

            _timer.Stop();
            _logger.Trace("Time elapsed for action \"{0}\": {1} msec", actionName, _timer.ElapsedMilliseconds);
        }

}
Run Code Online (Sandbox Code Playgroud)

但是,动作过滤器充当单例,因此在OnActionExecuted运行时,我无法确定_logger并且_timer对应于为同一动作OnActionExecuting创建的动作过滤器.

例如.

  1. Action Foo1开始执行._logger = "logger1",_timer = "timer1".
  2. Action Foo2开始执行._logger = "logger2",_timer = "timer2"(他们被覆盖)
  3. Action Foo1结束执行.它会停止计时器并记录经过的时间,这是无意义的(end1-start2).

:有没有一种方法我可以知道OnActionExecuted哪个OnActionExecuting它对应?如果有一些唯一的动作标识符,我可以将它用作Dictionary的一个键来存储任何与动作相关的对象,如记录器和定时器.有没有?或其他一些解决方案?

cle*_*ris 6

就Web API而言,System.Web.HttpContext.Current并不总能保证.这取决于您是否使用Web API Self托管.这是当覆盖System.Web.Http.Filters.ActionFilterAttribute.OnActionExecuting你没有在HttpActionContext参数上获得httpcontext属性的主要原因(你在AspNet MVC中).

做同样的最好的方法是actionContext.Request.Properties字典.

在这里查看这个答案