2
0

ReverseProxyApplicationBuilderExtensions.cs 1.7 KB

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