Skip to content

Instantly share code, notes, and snippets.

@Ekus
Created September 29, 2021 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ekus/e7436dd84615cc3b15c4b3049cc19fef to your computer and use it in GitHub Desktop.
Save Ekus/e7436dd84615cc3b15c4b3049cc19fef to your computer and use it in GitHub Desktop.
Add "page executed" timer to all asp.net views
Add this to the bottom of _Layout.cshtml, just before </body>
@if (User != null && User.IsAdmin() && ViewData.ContainsKey("_ElapsedTime"))
{
<div align="right">
Page action processed in @ViewData["_ElapsedTime"] ms
@if (ViewData.ContainsKey("_ActionTimer"))
{
<span>, total page in @((ViewData["_ActionTimer"] as System.Diagnostics.Stopwatch).ElapsedMilliseconds) ms</span>
}
</div>
}
// make all your MVC controllers inherit this one instead of System.Web.Mvc.Controller directly
using System.Web.Mvc;
using System.Diagnostics;
public class ApprovalController : Controller
{
static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
protected override void OnActionExecuting(ActionExecutingContext ctx)
{
// Start timing
var controller = this;
if (controller != null)
{
var timer = new Stopwatch();
controller.ViewData["_ActionTimer"] = timer;
timer.Start();
}
base.OnActionExecuting(ctx);
}
// Called after the action is executed
protected override void OnActionExecuted(ActionExecutedContext ctx)
{
base.OnActionExecuted(ctx);
var controller = this;
if (controller != null)
{
var timer = (Stopwatch)controller.ViewData["_ActionTimer"];
if (timer != null)
{
//timer.Stop();
controller.ViewData["_ElapsedTime"] = timer.ElapsedMilliseconds;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment