1. 程式人生 > >Action執行時間過濾器

Action執行時間過濾器

cti time attribute none tpc .info info 一個 單個

public class AccessStatisticsAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// log4net 日誌
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(typeof(AccessStatisticsAttribute));

        /// <summary>
        /// 該Action對應的權限項名稱
        
/// </summary> private readonly string _actionName; /// <summary> /// 該Action對應的權限項名稱 /// </summary> private readonly bool _logResult; /// <summary> /// .ctor /// </summary> public AccessStatisticsAttribute(string actionName, bool
logTheResult = false) { this._actionName = actionName; this._logResult = logTheResult; } /// <summary> /// 提供一個入口點用於進行自定義授權檢查 /// </summary> /// <param name="filterContext">HTTP 上下文,它封裝有關單個 HTTP 請求的所有 HTTP 特定的信息。</param>
public override void OnActionExecuting(ActionExecutingContext filterContext) { GetSessionTimer(filterContext).Start(); base.OnActionExecuting(filterContext); } /// <summary> /// OnActionExecuted /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuted(ActionExecutedContext filterContext) { var stopwatch = GetSessionTimer(filterContext); stopwatch.Stop(); var result = this._logResult ? filterContext.Result.ToJsonNoneFormat() : string.Empty; if (stopwatch.Elapsed.TotalMilliseconds > ActionHelper.ElapsedMillisecondsLimit) { Logger.InfoFormat("OUT : {0} {1} {2}ms {3}s", _actionName, result, (uint)stopwatch.Elapsed.TotalMilliseconds, (uint)stopwatch.Elapsed.TotalSeconds); } base.OnActionExecuted(filterContext); } private Stopwatch GetSessionTimer(ControllerContext context, string name = "actionElapse") { string key = name + "timer"; if (context.HttpContext.Items.Contains(key)) { return (Stopwatch)context.HttpContext.Items[key]; } var result = new Stopwatch(); context.HttpContext.Items[key] = result; return result; } }

Action執行時間過濾器