Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. public class RequestExecutionMiddleware
  2. {
  3. private readonly RequestDelegate _next;
  4. public RequestExecutionMiddleware(RequestDelegate next)
  5. {
  6. _next = next;
  7. }
  8. public async Task Invoke(HttpContext httpContext)
  9. {
  10. var watch = new Stopwatch();
  11.  
  12. httpContext.Response.OnStarting(() =>
  13. {
  14. watch.Stop();
  15. // here you can log it where you want.
  16. httpContext
  17. .Response
  18. .Headers
  19. .Add("X-Processing-Time-Milliseconds",
  20. new[] { watch.ElapsedMilliseconds.ToString() });
  21.  
  22. return Task.CompletedTask;
  23. });
  24.  
  25. watch.Start();
  26.  
  27. await _next(httpContext);
  28. }
  29. }
  30.  
  31. public static class CustomMiddlewareExtensions
  32. {
  33. public static IApplicationBuilder UseRequestExecutionMiddleware(this IApplicationBuilder builder)
  34. {
  35. return builder.UseMiddleware<RequestExecutionMiddleware>();
  36. }
  37. }
  38.  
  39. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  40. {
  41. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  42. loggerFactory.AddDebug();
  43.  
  44. if (env.IsDevelopment())
  45. {
  46. app.UseDeveloperExceptionPage();
  47. app.UseDatabaseErrorPage();
  48. }
  49. app.UseStaticFiles();
  50.  
  51. app.UseRequestExecutionMiddleware();
  52.  
  53. app.UseSession();
  54. app.UseMvc(route =>
  55. {
  56. route.MapRoute(
  57. name: "Default",
  58. template: "{controller=Home}/{action=Index}/{Id?}"
  59. );
  60. });
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement