Keith Hill
Keith Hill

Reputation: 202102

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?

Upvotes: 3

Views: 1351

Answers (2)

Chandu
Chandu

Reputation: 82963

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

Upvotes: 3

kevingessner
kevingessner

Reputation: 18995

I use the controller's Initialize method to set a flag in HttpContext.Items:

HttpContext.Items["StartTime"] = DateTime.Now;

Then print it in your view, or wherever:

<%
// We only set this in DEBUG builds
var startTime = HttpContext.Current.Items["StartTime"] as DateTime?
if(startTime.HasValue)
{ %>
    <%=(DateTime.Now - startTime.Value).TotalSeconds.ToString("0.00000")%> seconds
<%
}
%>

Upvotes: 1

Related Questions