如何在ASP.NET MVC中控制请求时间?

3

我熟悉使用HttpModule来计时请求,但这些并不能真正地钩入ASP.NET MVC的视图系统。是否可以通过在global.asax中启动计时器,然后在_layout.cshtml中访问它来实现?

2个回答

3

1) 您可以在应用程序类的Begin_Request和End_Request事件中检查请求的开始时间和结束时间。 2) 您可以定义自定义HttpModule。 3) 您可以定义一个自定义属性,如下所示:

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

有趣的方法 - 不知道这个属性。您能否在OnResultsExecuted重写中将HTML(即执行时间)注入到当前响应中? - Keith Hill
1
最干净的方法是在OnResultExecuting中将其添加到ViewData中,以便视图可以呈现它。显然,这不包括视图渲染时间,但任何可能耗时的事情都应该在控制器中完成。 - Tom Clarkson

1

我使用控制器的Initialize方法在HttpContext.Items中设置一个标志:

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

然后在您的视图或任何其他地方打印它:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接