页面生成时间-ASP.NETMVC

页面生成时间-ASP.NETMVC,asp.net,asp.net-mvc,Asp.net,Asp.net Mvc,我正在寻找一种方法来跟踪服务器生成页面所需的时间。我知道我可以使用跟踪跟踪这一点,但我需要一种方法来显示每页 它的ASP.NETMVC2将取决于您希望在何处包含此信息。例如,您可以编写一个http处理程序,在标记之后显示渲染时间: public class RenderTimeModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += (sen

我正在寻找一种方法来跟踪服务器生成页面所需的时间。我知道我可以使用跟踪跟踪这一点,但我需要一种方法来显示每页


它的ASP.NETMVC2

将取决于您希望在何处包含此信息。例如,您可以编写一个http处理程序,在
标记之后显示渲染时间:

public class RenderTimeModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += (sender, e) =>
        {
            var watch = new Stopwatch();
            var app = (HttpApplication)sender;
            app.Context.Items["Stopwatch"] = watch;
            watch.Start();
        };

        context.EndRequest += (sender, e) =>
        {
            var app = (HttpApplication)sender;
            var watch = (Stopwatch)app.Context.Items["Stopwatch"];
            watch.Stop();
            var ts = watch.Elapsed;
            string elapsedTime = String.Format("{0} ms", ts.TotalMilliseconds);
            app.Context.Response.Write(elapsedTime);
        };
    }

    public void Dispose()
    {
    }
}

如果您想在HTML页面中间显示某个渲染时间,那么这个渲染时间将不考虑总页面渲染时间。

< P>您可以像ActoFielter属性< /P>实现它。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class LoggingAttribute : ActionFilterAttribute
{
    private readonly Stopwatch _sw;

    public LoggingAttribute()
    {
        _sw = new Stopwatch();
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _sw.Start();
        Debug.WriteLine("Beginning executing: " + GetControllerAndActionName(filterContext.ActionDescriptor));
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        _sw.Stop();
        var ms = _sw.ElapsedMilliseconds;

        Debug.WriteLine("Finishing executing: " + GetControllerAndActionName(filterContext.ActionDescriptor));
        Debug.WriteLine("Time elapsed: "+ TimeSpan.FromMilliseconds(ms).TotalSeconds);
    }

    private string GetControllerAndActionName(ActionDescriptor actionDescriptor)
    {
        return actionDescriptor.ControllerDescriptor.ControllerName + " - " + actionDescriptor.ActionName;
    }
}

用它装饰每个控制器或动作方法,瞧,它在调试中吐出文本

编辑:如果要在页面上打印,可以将此代码段添加到OnActionExecuted方法中

if(filterContext.Result is ViewResult) { //Make sure the request is a ViewResult, ie. a page
  ((ViewResult) filterContext.Result).ViewData["ExecutionTime"] = ms; //Set the viewdata dictionary
}
现在,您已将executiontime保存在ViewData中,并可以在页面中访问它。。我通常这样把它放在母版上

<!-- The page took <%= ViewData["ExecutionTime"] %> ms to execute -->

是的,Derin建议是在ASP.NEt应用程序中执行此操作的标准方法,我只建议添加一个,如果这样做不会干扰非HTML响应: 编辑:添加了完整的实现

public class PerformanceMonitorModule : IHttpModule
{

    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += delegate(object sender, EventArgs e)
        {
            //Set Page Timer Star
            HttpContext requestContext = ((HttpApplication)sender).Context;
            Stopwatch timer = new Stopwatch();
            requestContext.Items["Timer"] = timer;
            timer.Start();
             };
        context.PostRequestHandlerExecute += delegate(object sender, EventArgs e)
        {

            HttpContext httpContext = ((HttpApplication)sender).Context;
            HttpResponse response = httpContext.Response;
            Stopwatch timer = (Stopwatch)httpContext.Items["Timer"];
            timer.Stop();

            // Don't interfere with non-HTML responses
            if (response.ContentType == "text/html")
            {
                double seconds = (double)timer.ElapsedTicks / Stopwatch.Frequency;
                string result_time = string.Format("{0:F4} sec ", seconds);
                RenderQueriesToResponse(response,result_time);
            }
        };
    }
    void RenderQueriesToResponse(HttpResponse response, string result_time)
    {
        response.Write("<div style=\"margin: 5px; background-color: #FFFF00\"");
        response.Write(string.Format("<b>Page Generated in "+ result_time));
        response.Write("</div>");
    }
    public void Dispose() { /* Not needed */ }
}
公共类性能监视器模块:IHttpModule
{
公共void Init(HttpApplication上下文)
{
context.PreRequestHandlerExecute+=委托(对象发送方,事件参数e)
{
//设置页面计时器星号
HttpContext requestContext=((HttpApplication)sender.Context;
秒表计时器=新秒表();
requestContext.Items[“Timer”]=计时器;
timer.Start();
};
context.PostRequestHandlerExecute+=委托(对象发送方,事件参数e)
{
HttpContext HttpContext=((HttpApplication)发送方).Context;
HttpResponse response=httpContext.response;
秒表计时器=(秒表)httpContext.Items[“timer”];
timer.Stop();
//不要干扰非HTML响应
if(response.ContentType==“text/html”)
{
双秒=(双)timer.ElapsedTicks/Stopwatch.Frequency;
string result_time=string.Format(“{0:F4}秒”,秒);
RenderQueriesToResponse(响应、结果和时间);
}
};
}
void RenderQueriesToResponse(HttpResponse响应,字符串结果\u时间)
{

response.Write(“这似乎是在断开我的页面的元素之后输出的:(建议?是的,这是我在帖子中说的。如果你不想破坏验证,你可以把它放在评论中。这种方法适用于Json和文件结果,还是仅适用于html?谢谢-效果很好,除了在破坏我页面的元素后输出外:(建议?这是添加的(追加)作为响应的一部分,它可能不是在HTML结束标记之后。我用一个示例img编辑我的帖子,我已经有一个项目正在运行并测试它,我不知道Darin为什么在HTML之后说它…?,也许他提到了另一个实现。你能发布完整的示例吗?目前的代码显示在标记下面。装饰每个控制器或控制器动作方法有点痛苦,因为我们有很多(相当大的项目)-无论如何,我们可以在不做如此大的更改的情况下将这个工作站点扩展?在我的项目中,我的所有控制器都继承自BaseController。所以我只装饰BaseController,它反过来“装饰”"正在执行所有操作方法。这是一种非常好的方法,值得一提的是,它实际上跟踪的是控制器的生命周期,而不是总的请求生命周期。@Pino-使用ASP.NET MVC3,您可以在
应用程序启动期间
处理程序将该属性添加到GlobalFiltersCollection中,以避免修饰每个类/操作h it.运行时间不应该在ResultExecuted而不是OnActionExecuted上计算吗?
  <add name="Name" type="namespace, dll"/>