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?.
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());
}
}
Use MiniProfiler, from the makers of StackOverflow. Very easy to use, and by default gives measurements such as the execution of controller actions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With