ReverseProxyApplicationBuilderExtensions.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using FastGithub.Scanner;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using System.Net.Http;
  6. using Yarp.ReverseProxy.Forwarder;
  7. namespace FastGithub
  8. {
  9. /// <summary>
  10. /// gitub反向代理的中间件扩展
  11. /// </summary>
  12. public static class ReverseProxyApplicationBuilderExtensions
  13. {
  14. /// <summary>
  15. /// 使用gitub反向代理中间件
  16. /// </summary>
  17. /// <param name="app"></param>
  18. /// <returns></returns>
  19. public static IApplicationBuilder UseGithubReverseProxy(this IApplicationBuilder app)
  20. {
  21. var httpForwarder = app.ApplicationServices.GetRequiredService<IHttpForwarder>();
  22. var httpClientHanlder = app.ApplicationServices.GetRequiredService<GithubHttpClientHanlder>();
  23. var githubResolver = app.ApplicationServices.GetRequiredService<IGithubResolver>();
  24. app.Use(next => async context =>
  25. {
  26. var host = context.Request.Host.Host;
  27. if (githubResolver.IsSupported(host) == false)
  28. {
  29. await context.Response.WriteAsJsonAsync(new { message = $"不支持以{host}访问" });
  30. }
  31. else
  32. {
  33. var port = context.Request.Host.Port ?? 443;
  34. var destinationPrefix = $"http://{host}:{port}/";
  35. var httpClient = new HttpMessageInvoker(httpClientHanlder, disposeHandler: false);
  36. await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
  37. }
  38. });
  39. return app;
  40. }
  41. }
  42. }