除了回答https://stackoverflow.com/a/5823555/504082之外,更正确的方法是在时钟执行结束时使用 OnResultExecuted 覆盖。你什么时候回来
ActionResponse.Success(arr.Select(x => func(x)).ToJson();
即由于您的操作而导致的一些惰性 LINQ 语句,它将在操作“执行”后计算(函数 'func' 执行将不计入操作执行时间)。我有这个讨厌的错误,无法弄清楚为什么我的动作“执行时间”是 100 毫秒,尽管网络请求执行 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());
}
}
}