除了回答https://stackoverflow.com/a/5823555/504082之外,更正確的方法是在時鐘執行結束時使用OnResultExecuted覆蓋。 當您返回
ActionResponse.Success(arr.Select(x => func(x)).ToJson();
即有些慵懶LINQ語句作爲你的行爲的結果,它會被計算後被「執行」行動(函數「功能」的執行不會對動作執行時間算) 。 我有這個討厭的錯誤,不知道爲什麼我的行動「執行時間」是100毫秒,雖然Web請求執行10秒。下面修改的代碼。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SW
{
public class StopwatchAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var stopwatch = new Stopwatch();
filterContext.HttpContext.Items["Stopwatch"] = stopwatch;
stopwatch.Start();
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var stopwatch = (Stopwatch)filterContext.HttpContext.Items["Stopwatch"];
stopwatch.Stop();
var httpContext = filterContext.HttpContext;
var response = httpContext.Response;
response.AddHeader("X-Runtime", stopwatch.Elapsed.TotalMilliseconds.ToString());
}
}
}
是啊,緩存關閉在Firefox ... – ullmark 2011-04-28 15:52:42