PipelineBuilderExtensions.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. namespace FastGithub
  3. {
  4. /// <summary>
  5. /// 中间件创建者扩展
  6. /// </summary>
  7. public static class PipelineBuilderExtensions
  8. {
  9. /// <summary>
  10. /// 中断执行中间件
  11. /// </summary>
  12. /// <typeparam name="TContext"></typeparam>
  13. /// <param name="builder"></param>
  14. /// <param name="handler">处理者</param>
  15. /// <returns></returns>
  16. public static IPipelineBuilder<TContext> Run<TContext>(this IPipelineBuilder<TContext> builder, InvokeDelegate<TContext> handler)
  17. {
  18. return builder.Use(_ => handler);
  19. }
  20. /// <summary>
  21. /// 条件中间件
  22. /// </summary>
  23. /// <typeparam name="TContext"></typeparam>
  24. /// <param name="builder"></param>
  25. /// <param name="predicate"></param>
  26. /// <param name="handler"></param>
  27. /// <returns></returns>
  28. public static IPipelineBuilder<TContext> When<TContext>(this IPipelineBuilder<TContext> builder, Func<TContext, bool> predicate, InvokeDelegate<TContext> handler)
  29. {
  30. return builder.Use(next => async context =>
  31. {
  32. if (predicate.Invoke(context) == true)
  33. {
  34. await handler.Invoke(context);
  35. }
  36. else
  37. {
  38. await next(context);
  39. }
  40. });
  41. }
  42. /// <summary>
  43. /// 条件中间件
  44. /// </summary>
  45. /// <typeparam name="TContext"></typeparam>
  46. /// <param name="builder"></param>
  47. /// <param name="predicate"></param>
  48. /// <param name="configureAction"></param>
  49. /// <returns></returns>
  50. public static IPipelineBuilder<TContext> When<TContext>(this IPipelineBuilder<TContext> builder, Func<TContext, bool> predicate, Action<IPipelineBuilder<TContext>> configureAction)
  51. {
  52. return builder.Use(next => async context =>
  53. {
  54. if (predicate.Invoke(context) == true)
  55. {
  56. var branchBuilder = builder.New();
  57. configureAction(branchBuilder);
  58. await branchBuilder.Build().Invoke(context);
  59. }
  60. else
  61. {
  62. await next(context);
  63. }
  64. });
  65. }
  66. }
  67. }