开发期间,将开发过程中常用的内容做个收藏,如下内容内容是关于asp.net mvc 获取页面执行时间的类的内容,希望对各朋友有些用。
[csharp] view plaincopy
public class PerformanceActionAttributeFilter : ActionFilterAttribute
{
public string Message { get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
GetTimer(filterContext, "action").Stop();
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
GetTimer(filterContext, "action").Start();
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var renderTimer = GetTimer(filterContext, "render");
renderTimer.Stop();
var actionTimer = GetTimer(filterContext, "action");
var response = filterContext.HttpContext.Response;
if (response.ContentType == "text/html")
{
response.Write(
String.Format(
"<p>Action '{0} :: {1}', Execute: {2}ms, Render: {3}ms.</p>",
filterContext.RouteData.Values["controller"],
filterContext.RouteData.Values["action"],
actionTimer.ElapsedMilliseconds,
renderTimer.ElapsedMilliseconds
)
);
}
base.OnResultExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
GetTimer(filterContext, "render").Start();
base.OnResultExecuting(filterContext);
}
private Stopwatch GetTimer(ControllerContext context, string name)
{
string key = "__timer__" + name;
if (context.HttpContext.Items.Contains(key))
{
return (Stopwatch)context.HttpContext.Items[key];
}
var result = new Stopwatch();
context.HttpContext.Items[key] = result;
return result;
}
}
2)在Controller中添加描述
[PerformanceActionAttributeFilter(Message ="controller")]
public class HomeController : Controller
{
[PerformanceActionAttributeFilter(Message = "action")]
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
网友评论