我想通过母版页向我的所有 ASP.NET MVC 页面添加一个输出,显示当前页面的呈现时间。我怎么能这样做?
最佳答案
这很棘手,因为在呈现页面之前,您必须将所有 ViewData 添加到其中。
您可以通过编写自定义 ActionFilterAttribute
并重写 OnActionExecuting
来启动计时器和 OnActionExecuted
来获取执行 Controller 操作所花费的总时间code> 获取耗时并将其存储到 ViewData
。执行 ActionResult 时,它可能会花时间将其呈现到您的 View 中。
这可能足以满足您的需求?不幸的是,要获得正在执行的 Action 和 Result 的总时间,您需要在 Controller 中覆盖 OnActionExecuting
和 OnResultExecuted
,但在这一点上它太迟到向 View 添加信息,因为它已经呈现。你可以 log it to a file however, see this link for an example .
好的,这是一个示例计时器操作过滤器。将其作为一个类添加到您的项目中,然后您可以使用 [ActionTimer]
标记任何 Controller 方法,它会将耗时添加到名为“_ElapsedTime
”的 ViewData 存储桶中",您可以在 View 中打印出来。
using System.Web.Mvc;
using System.Diagnostics;
namespace MvcApplication1 {
public class ActionTimerAttribute : ActionFilterAttribute
{
public ActionTimerAttribute()
{
// Make sure this attribute executes after every other one!
this.Order = int.MaxValue;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller;
if (controller != null)
{
var timer = new Stopwatch();
controller.ViewData["_ActionTimer"] = timer;
timer.Start();
}
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var controller = filterContext.Controller;
if (controller != null)
{
var timer = (Stopwatch)controller.ViewData["_ActionTimer"];
if (timer != null)
{
timer.Stop();
controller.ViewData["_ElapsedTime"] = timer.ElapsedMilliseconds;
}
}
}
} }
正如我之前提到的,这不包括实际呈现 ActionResult
所花费的时间。如果您看一下我链接的示例,它会向您展示如何对日志文件执行此操作,并让您了解如何使用四个操作过滤器事件。
关于C# ASP.NET MVC : Show Page Render Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1428785/