7月 27

我在这里主要用来监控每个页面的执行时间

    public class VisitLogFilter : IActionFilter
    {
        private const string DURATION = "DURATION";

        public void OnActionExecuted(ActionExecutedContext context)
        {

            var stopwach = context.RouteData.Values[DURATION] as Stopwatch;
            stopwach.Stop();
            var time = stopwach.Elapsed;

            var url = context.HttpContext.Request.Host + context.HttpContext.Request.Path;
            var agent = ((FrameRequestHeaders)context.HttpContext.Request.Headers).HeaderUserAgent.ToString();
            var ip = IPHelper.GetUserIp(context.HttpContext);
            LogHelper.Info(time.TotalMilliseconds + "\t\t" + ip + "\t\t" + url + "\t\t\t\t" + agent);

            if (context.Result is ViewResult)
            {
                ((ViewResult)context.Result).ViewData[DURATION] = (time.TotalMilliseconds).ToString("#.##");
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var stopwach = new Stopwatch();
            stopwach.Start();
            context.RouteData.Values.Add(DURATION, stopwach);           
        }

    }

 

注入全局

            services.AddMvc(
                config =>
                {
                    config.Filters.Add(new VisitLogFilter()); 
                });

前台展示的代码

                        @if (ViewData.ContainsKey("DURATION"))
                        {
                            <p>页面执行时间 : @(ViewData["DURATION"]) ms.</p>
                        }

written by ocean


Leave a Reply