Search code examples
asp.net-mvchttpmodule

How can you time requests with ASP.NET MVC?


I'm familiar with using a HttpModule to time requests but those don't really hook into ASP.NET MVC's view system. Can this be done by starting a timer somewhere in global.asax and then accessing it in _layout.cshtml?


Solution

  • 1) You can check the start time and end time of a request in Begin_Request and End_Request events of application class 2) You can define a custom HttpModule 3)You can define a custom attribute as follows:

    public class RequestTimerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Mark the Start Time 
                    MarkTime("Start");
        }
    
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            //Mark the Start Time 
                    MarkTime("End");
        }
    
        void MarkTime(string EventName)
        {
            //Handle the logic here to log the time 
        }        
    }