Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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...

Thanks for any help!

share|improve this question
1  
System.Diagnostics.Stopwatch? – Joe Jun 12 '13 at 15:18
    
Also check this article for both MVC APIs and Web APIs. – Massood Khaari Jun 29 '15 at 14:41
up vote 18 down vote accepted

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.

share|improve this answer
    
Thank you so much Dean! This is the perfect solution! – RooSoft Jun 12 '13 at 17:45
    
Why do u save the instance in the request ? Why don't u make it a private field ? – user49126 Sep 23 '14 at 17:35
3  
@user49126 Action filters are shared across multiple actions and there could be multiple in-flight requests. To eliminate concurrency concerns it is safest to store the instance on the request. – Dean Ward Sep 24 '14 at 10:59
    
Also there is an improved solution stays here link – zapoo Aug 5 '15 at 12:06
    
Does this work for async methods? i.e. If using async then will this time the duration of the call including all continuations until the bytes are written to the response stream? – Luke Puplett Oct 23 '15 at 15:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.