YARP簡介 —— IHttpProxy


YARP框架中,核心處理類是IHttpProxy,其接口定義如下:

Task ProxyAsync(HttpContext context, string destinationPrefix, HttpMessageInvoker httpClient, RequestProxyOptions requestOptions, HttpTransformer transformer)

從它的接口定義基本可以看出它的功能:從 HttpContext 創建 Http 查詢信息、發送到目標地址,並將響應結果寫會HttpContext。

IhttpProxy特點如下:

  1. 靈活,能根據請求動態選擇代理目標
  2. 強大,能修改http請求和響應的頭
  3. 支持gRPC或WebSockets這種流式協議
  4. 支持異常處理

它簡單靈活,本身是一個反向代理的功能類的。 用它本身是可以非常簡單的實現一個反向代理功能的。代碼如下: 

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddHttpProxy();
 4 }
 5 
 6 public void Configure(IApplicationBuilder app, IHttpProxy httpProxy)
 7 {
 8     var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
 9     {
10         UseProxy = false,
11         AllowAutoRedirect = false,
12         AutomaticDecompression = DecompressionMethods.None,
13         UseCookies = false
14     });
15     var transformer = new CustomTransformer(); // or HttpTransformer.Default;
16     var requestOptions = new RequestProxyOptions { Timeout = TimeSpan.FromSeconds(100) };
17 
18     app.UseRouting();
19     app.UseAuthorization();
20     app.UseEndpoints(endpoints =>
21     {
22         endpoints.Map("/{**catch-all}", async httpContext =>
23         {
24             await httpProxy.ProxyAsync(httpContext, "https://localhost:10000/", httpClient,
25                 requestOptions, transformer);
26 
27             var errorFeature = httpContext.GetProxyErrorFeature();
28             if (errorFeature != null)
29             {
30                 var error = errorFeature.Error;
31                 var exception = errorFeature.Exception;
32             }
33         });
34     });
35 }
View Code

這里為了演示請求和相應頭的功能,自定義了一個HttpTransformer,代碼如下。 

 1 private class CustomTransformer : HttpTransformer
 2 {
 3     public override async Task TransformRequestAsync(HttpContext httpContext,
 4         HttpRequestMessage proxyRequest, string destinationPrefix)
 5     {
 6         // Copy headers normally and then remove the original host.
 7         // Use the destination host from proxyRequest.RequestUri instead.
 8         await base.TransformRequestAsync(httpContext, proxyRequest, destinationPrefix);
 9         proxyRequest.Headers.Host = null;
10     }
11 }
View Code

上述代碼本身是實現了一個完整的的反向代理的功能的。和目前的主流的反向代理框架比起來,主要缺少一些高級功能,如:路由匹配、負載均衡、會話保持、重試等。但這些高級功能本身不是必須的,這個時候直接用IhttpProxy更加簡單直接,也可以方便我們自己構建一個更加靈活高效的反向代理框架。

參考文章:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM