How can you request time using ASP.NET MVC?

I am familiar with using the HttpModule for time queries, but in fact they do not connect to the ASP.NET MVC view system. Can this be done by starting the timer somewhere in global.asax and then getting it in _layout.cshtml?

+3
source share
2 answers

1) You can check the start and end times of the request in the Begin_Request and End_Request events of the application class 2) You can define a custom HttpModule 3) You can define a custom attribute as follows:

public class RequestTimerAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Mark the Start Time 
                MarkTime("Start");
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //Mark the Start Time 
                MarkTime("End");
    }

    void MarkTime(string EventName)
    {
        //Handle the logic here to log the time 
    }        
}
+3
source

I use the Initializecontroller method to set the flag to HttpContext.Items:

HttpContext.Items["StartTime"] = DateTime.Now;

Then print it in your view or anywhere:

<%
// We only set this in DEBUG builds
var startTime = HttpContext.Current.Items["StartTime"] as DateTime?
if(startTime.HasValue)
{ %>
    <%=(DateTime.Now - startTime.Value).TotalSeconds.ToString("0.00000")%> seconds
<%
}
%>
+1
source

Source: https://habr.com/ru/post/1783453/


All Articles