ListenOptionsExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using FastGithub.FlowAnalyze;
  2. using Microsoft.AspNetCore.Server.Kestrel.Core;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace FastGithub
  5. {
  6. /// <summary>
  7. /// ListenOptions扩展
  8. /// </summary>
  9. public static class ListenOptionsExtensions
  10. {
  11. /// <summary>
  12. /// 使用流量分析中间件
  13. /// </summary>
  14. /// <param name="listen"></param>
  15. /// <returns></returns>
  16. public static ListenOptions UseFlowAnalyze(this ListenOptions listen)
  17. {
  18. var flowAnalyzer = listen.ApplicationServices.GetRequiredService<IFlowAnalyzer>();
  19. listen.Use(next => async context =>
  20. {
  21. var oldTransport = context.Transport;
  22. try
  23. {
  24. await using var loggingDuplexPipe = new FlowAnalyzeDuplexPipe(context.Transport, flowAnalyzer);
  25. context.Transport = loggingDuplexPipe;
  26. await next(context);
  27. }
  28. finally
  29. {
  30. context.Transport = oldTransport;
  31. }
  32. });
  33. return listen;
  34. }
  35. }
  36. }