开发者

How can you time requests with ASP.NET MVC?

I'm familiar with usi开发者_JS百科ng 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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜