【发布时间】:2014-08-14 16:03:38
【问题描述】:
我有一个名为“PerformanceHandler”的委托处理程序。我想记录所有进来的请求的响应时间。
我创建了一个 StopWatch 并在 SendAsync 中启动它,然后使用以下命令返回它: 返回 base.SendAsync(request, cancelToken).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
}
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4