Install-Package Microsoft.AspNetCore.Proxy -Version 0.2.0
该中间件目前只有 2 个扩展方法, 主要关注如下扩展方法:
- //
- // 摘要:
- // Sends request to remote server as specified in options
- //
- // 参数:
- // App:
- //
- // options:
- // Options for setting port, host, and scheme
- public static IApplicationBuilder RunProxy(this IApplicationBuilder App, ProxyOptions options);
本次代理请求需要携带 BA 凭据, 所以可在 ProxyOptions 参数设定基本身份认证 Handler:
- public void ConfigureServices(IServiceCollection services)
- {
- _remoteAccount = services.ConfigureOption<RemoteBasicAuth>(Configuration.GetSection("RemoteBasicAuth"));
- _proxyOption = services.ConfigureOption<ProxyOptions>(Configuration.GetSection("ProxyOptions"));
- // 从本地配置文件读取云服务器 B 的认证凭据, 并设置基本身份认证 Handler
- _proxyOption.BackChannelMessageHandler = new BasicAuthenticationClientHandler(_remoteAccount);
- ......
- }
该云服务器 B 在部分页面[url 以 / eqids 开头, API 以 / API/v1/eqids/] 配置了 BA 认证:
所以本次我们使用了 MapWhen 条件中间件:
- public void Configure(IApplicationBuilder App, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, Microsoft.Extensions.Hosting.IApplicationLifetime appLifetime, ILoggerFactory loggerFactory)
- {
- ......
- App.MapWhen(x=>
- x.Request.Path.Value.StartsWith(@"/eqids", StringComparison.OrdinalIgnoreCase) ||
- x.Request.Path.Value.StartsWith(@"/api/v1/eqids", StringComparison.OrdinalIgnoreCase),
- builder => builder.RunProxy(_proxyOption));
- ......
- }
That's All. 以上程序部署到服务器 A 之后, 这样访问服务器 A 的部署网站, 等同于访问云服务器 B 的资源, 服务器 B 对于内网来说是透明的.
本文期待以一种轻松, 优雅的方式快速实现一个具备自定义消息处理能力的 web 代理服务器.
---------- 如有问题请大胆斧正; 你觉得文章对你有价值, 请 或加关注, 蟹蟹 -----------~~..~~------------
来源: https://www.cnblogs.com/mi12205599/p/10503600.html