ReverseProxyApplicationBuilderExtensions.cs 1.9 KB

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