I am using an ActionFilter to log all action calls of my ASP.NET Web API project. The OnActionExecuted method tells a lot about what's been happening.
I just can't figure out how to find an efficient way to measure execution time...
I am using an ActionFilter to log all action calls of my ASP.NET Web API project. The OnActionExecuted method tells a lot about what's been happening.
I just can't figure out how to find an efficient way to measure execution time...
Something like this should do the trick...
public class StopwatchAttribute : ActionFilterAttribute
{
private const string StopwatchKey = "StopwatchFilter.Value";
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
actionContext.Request.Properties[StopwatchKey] = Stopwatch.StartNew();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
Stopwatch stopwatch = (Stopwatch)actionExecutedContext.Request.Properties[StopwatchKey];
// TODO something useful with stopwatch.Elapsed
Trace.WriteLine("Elapsed = " + stopwatch.Elapsed);
}
}
Here we store a new Stopwatch
in the request properties and stop it when the request has completed.
Stopwatch
works by taking a snapshot of the system ticks when started and computing the difference from that snapshot when queried. In this case though we're using an action filter so it only includes the time that it takes to execute the action itself. If you need to get timing information for the full request you should look into the Tracing API instead.
Commented
Oct 24, 2015 at 19:02
You will need these using statements to run the above example:
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
I registered the filter globally for my whole api in WebApiConfig class like this: config.Filters.Add(new StopwatchAttribute());
and in case you want to print out the name of the controller with the elapsed time, here is how you can get the name of the controller in the OnActionExectued method:
string ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;