Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the elapsed time of executing action in MVC

Tags:

c#

asp.net-mvc

I want to calculate the elapsed time any action and save it in the database. i dont Use stopwatch in all actions.

I am looking for a way that can be applied to the entire project asp.net MVC in other word There is an event that happens in every time executed a action?.

like image 882
Morteza Jangjoo Avatar asked Sep 13 '25 15:09

Morteza Jangjoo


2 Answers

You have to do something like this. 1. Create Filter.

public class ActionExecutionTimeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Items["ActionName"] = filterContext.HttpContext.Request.RawUrl;
            filterContext.HttpContext.Items["StartTime"] = DateTime.UtcNow;
            base.OnActionExecuting(filterContext);
        }
        // Do this to calculate only Action Execution Time
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            DateTime startTime = (DateTime)filterContext.HttpContext.Items["StartTime"];
            System.Diagnostics.Debug.WriteLine(filterContext.HttpContext.Items["ActionName"].ToString() + "-" + (DateTime.UtcNow - startTime).TotalMilliseconds);
        }
        // Do this to calcution of Action Start to Result Process
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            DateTime startTime = (DateTime)filterContext.HttpContext.Items["StartTime"];
            System.Diagnostics.Debug.WriteLine(filterContext.HttpContext.Items["ActionName"].ToString() + "- (R)" + (DateTime.UtcNow - startTime).TotalMilliseconds);
        }
    }

2. Register in Global.asax

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new ActionExecutionTimeAttribute());
    }
}
  1. You have to do How to insert data in DB.
like image 59
dotnetstep Avatar answered Sep 16 '25 04:09

dotnetstep


Use MiniProfiler, from the makers of StackOverflow. Very easy to use, and by default gives measurements such as the execution of controller actions.

like image 24
Maarten Avatar answered Sep 16 '25 04:09

Maarten