如何在DelegatingHandler中记录响应时间

本文关键字:记录 响应时间 DelegatingHandler | 更新日期: 2023-09-27 18:17:57

我有一个委托处理程序称为"PerformanceHandler"。我想记录所有传入请求的响应时间。

我创建了一个秒表,并在SendAsync中启动它,然后使用:返回基地。非同步请求,cancellationToken .ContinueWith。然而,当我尝试这样做时,所有的请求似乎永远不会返回,而且它根本不记录时间。

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

My Global.asax.cs包含:

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

My PerformanceHandler.cs code:

    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
        }
   }

如何在DelegatingHandler中记录响应时间

我认为下面的修改可以工作。

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;
        }
   }