The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PerformanceMonitorMiddleware.cs 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Http;
  8. using Teknik.Configuration;
  9. using Teknik.Utilities;
  10. namespace Teknik.Middleware
  11. {
  12. // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
  13. public class PerformanceMonitorMiddleware
  14. {
  15. private readonly RequestDelegate _next;
  16. public PerformanceMonitorMiddleware(RequestDelegate next)
  17. {
  18. _next = next;
  19. }
  20. public async Task Invoke(HttpContext httpContext, Config config)
  21. {
  22. Stopwatch timer = new Stopwatch();
  23. timer.Start();
  24. httpContext.Response.OnStarting(state =>
  25. {
  26. var context = (HttpContext)state;
  27. timer.Stop();
  28. double ms = (double)timer.ElapsedMilliseconds;
  29. string result = string.Format("{0:F0}", ms);
  30. if (!httpContext.Response.Headers.IsReadOnly)
  31. httpContext.Response.Headers.Add("GenerationTime", result);
  32. return Task.CompletedTask;
  33. }, httpContext);
  34. await _next(httpContext);
  35. // Don't interfere with non-HTML responses
  36. if (httpContext.Response.ContentType != null && httpContext.Response.ContentType.StartsWith("text/html") && httpContext.Response.StatusCode == 200 && !httpContext.Request.IsAjaxRequest())
  37. {
  38. double ms = (double)timer.ElapsedMilliseconds;
  39. string result = string.Format("{0:F0}", ms);
  40. await httpContext.Response.WriteAsync(
  41. "<script nonce=\"" + httpContext.Items[Constants.NONCE_KEY] + "\">" +
  42. "var pageGenerationTime = '" + result + "';" +
  43. "pageloadStopTimer();" +
  44. "</script >");
  45. }
  46. }
  47. }
  48. // Extension method used to add the middleware to the HTTP request pipeline.
  49. public static class PerformanceMonitorMiddlewareExtensions
  50. {
  51. public static IApplicationBuilder UsePerformanceMonitor(this IApplicationBuilder builder)
  52. {
  53. return builder.UseMiddleware<PerformanceMonitorMiddleware>();
  54. }
  55. }
  56. }