Created
September 29, 2021 16:07
-
-
Save Ekus/e7436dd84615cc3b15c4b3049cc19fef to your computer and use it in GitHub Desktop.
Add "page executed" timer to all asp.net views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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