你怎么能用ASP.NET MVC来请求时间?

时间:2011-01-04 17:36:04

标签: asp.net-mvc httpmodule

我熟悉使用HttpModule来计时请求,但那些并没有真正挂钩到ASP.NET MVC的视图系统。可以通过在global.asax中的某个位置启动计时器然后在_layout.cshtml中访问它来完成吗?

2 个答案:

答案 0 :(得分: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 
    }        
}

答案 1 :(得分: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
<%
}
%>