How to calculate all action running time in asp.net mvc5 with custom action filter?

1.3k views Asked by At

I want to log execution time of almost all actions in asp.net mvc5 but basically doing this with below code is the correct way or it makes the project very slow ? Any suggestion?

    Stopwatch sw = new Stopwatch();
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        sw.Start();
        base.OnActionExecuting(filterContext);
    }
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        sw.Stop();
        float f = sw.ElapsedMilliseconds;
        base.OnActionExecuted(filterContext);
    }
1

There are 1 answers

0
Jim On BEST ANSWER

I would perhaps store the timing in a appropriately scoped location, perhaps on the request.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    filterContext.HttpContext.Items["timer"] = Stopwatch.StartNew();
    base.OnActionExecuting(filterContext);
}

that way you avoid using a cumbersome dictionary, and your timer is on a per request basis.

You can then cast the value in OnActionExecuted

        var sw = filterContext.HttpContext.Items["timer"] as Stopwatch;
        sw.ElapsedMilliseconds...