如何在DelegatingHandler中记录响应时间?

时间:2014-08-14 16:03:39

标签: c# asp.net-mvc asp.net-mvc-4

我有一个名为“PerformanceHandler”的委托处理程序。我想记录所有请求的响应时间。

我创建了一个StopWatch并在SendAsync中启动它,然后使用以下命令返回: return base.SendAsync(request,cancellationToken).ContinueWith。但是,当我尝试这个时,所有请求似乎永远不会返回,并且它根本不记录时间。

我做错了什么?如果这段代码没有意义,那么在DelegatingHandler中记录请求时间的正确方法是什么?

我的Global.asax.cs包含:

GlobalConfiguration.Configuration.MessageHandlers.Add(new PerformanceHandler());

我的PerformanceHandler.cs代码:

    public class PerformanceHandler : DelegatingHandler
    {
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            request.Properties.Add(new KeyValuePair<string, object>("Stopwatch", stopwatch));

            return base.SendAsync(request, cancellationToken).ContinueWith(t =>
            {
                Log(request, t.Result);
                return t.Result;
            });

        }

        private void Log(HttpRequestMessage request, HttpResponseMessage response)
        {
            var requestMethod = request.Method.Method;
            var requestUri = request.RequestUri.ToString();

            var stopwatch = (Stopwatch)request.Properties["Stopwatch"];
            stopwatch.Stop();

            var responseTimeInMilliseconds = 1000; //stopwatch.ElapsedMilliseconds;

            int userObjectId = UserSession.Current().UserObjectId;

            System.Diagnostics.Debug.WriteLine("End of Request");

            //LOG TIME HERE
        }

   }

1 个答案:

答案 0 :(得分:0)

我认为以下修改可行。

public class PerformanceHandler : DelegatingHandler
    {
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            request.Properties.Add(new KeyValuePair<string, object>("Stopwatch", stopwatch));

            var response = await base.SendAsync(request, cancellationToken);

            Log(request, response);

            return response;

        }
   }