如何使用 ASP.NET MVC 计时请求?

发布于 2024-10-10 18:47:20 字数 116 浏览 0 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始终不够爱げ你 2024-10-17 18:47:21

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) 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 
    }        
}
傲鸠 2024-10-17 18:47:21

我使用控制器的 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
<%
}
%>

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
<%
}
%>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文