1
我正在开发一个ASP.net Web API 2项目,并希望基准每个控制器操作的时间。我的想法是使用ActionFilterAttribute并在包含所花费时间的响应中添加一个http标头。基准测试ASP.net Web API操作
控制器:
[Timing]
public class MyController : ApiController
{
[Route("get")]
public IHttpActionResult Get() {
System.Threading.Thread.Sleep(1000);
return Ok();
}
}
ActionFilterAttribute:
public class TimingAttribute : ActionFilterAttribute
{
private System.Diagnostics.Stopwatch timer;
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
timer = System.Diagnostics.Stopwatch.StartNew();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
timer.Stop();
if (actionExecutedContext.Response != null && actionExecutedContext.Response.Content !=null)
{
actionExecutedContext.Response.Content.Headers.TryAddWithoutValidation("Execution-time", timer.ElapsedMilliseconds.ToString());
}
}
}
当我跑,我得到小于1秒的执行时间,即使我有一个控制器中的1秒的延迟。有谁知道为什么会出现这种情况,或者有更好的方法来测试Web API 2吗?