.NET Core 8配置YARP反向代理(公网IP/端口)及iframe Cookie处理
解决方案
1. 实现公网IP访问的反向代理并在iframe展示
步骤1:修正Program.cs的YARP配置与服务注册
确保应用监听公网IP,同时正确配置YARP的路由转发规则:
var builder = WebApplication.CreateBuilder(args); // 注册YARP反向代理服务 builder.Services.AddReverseProxy() .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); // 注册控制器服务 builder.Services.AddControllersWithViews(); var app = builder.Build(); // 让应用监听公网IP(服务器部署时需确保对应端口防火墙已开放) app.Urls.Add("http://0.0.0.0:你的公网端口"); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // 映射YARP代理端点 app.MapReverseProxy(); // 映射控制器默认路由 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
在appsettings.json中配置YARP转发规则(替换https://target.example.com为你的目标URL):
{ "ReverseProxy": { "Routes": { "proxy-route": { "ClusterId": "target-cluster", "Match": { "Path": "/proxy/{**catch-all}" } } }, "Clusters": { "target-cluster": { "Destinations": { "target-destination": { "Address": "https://target.example.com/" } } } } } }
步骤2:修正HomeController的Proxy逻辑
无需手动使用HttpClientFactory,YARP已封装完整代理逻辑,你可以选择直接复用YARP路由,或通过IHttpForwarder自定义代理:
public class HomeController : Controller { private readonly IHttpForwarder _httpForwarder; private readonly HttpMessageInvoker _httpClient; public HomeController(IHttpForwarder httpForwarder) { _httpForwarder = httpForwarder; // 初始化YARP需要的HttpMessageInvoker _httpClient = new HttpMessageInvoker(new SocketsHttpHandler { AllowAutoRedirect = false, UseProxy = false, EnableMultipleHttp2Connections = true, PooledConnectionLifetime = TimeSpan.FromMinutes(10) }); } public IActionResult Index() { // 传递公网代理地址到视图 ViewData["ProxyUrl"] = $"http://你的公网IP:你的公网端口/proxy"; return View(); } // 自定义代理Action(若需额外业务逻辑) public async Task Proxy() { // 拼接目标请求地址 var targetPath = Request.Path.Value.Replace("/Home/Proxy", ""); var targetUri = new Uri($"https://target.example.com{targetPath}"); // 执行YARP转发 var error = await _httpForwarder.SendAsync(HttpContext, targetUri.AbsoluteUri, _httpClient); if (error != ForwarderError.None) { // 处理代理错误逻辑 var errorFeature = HttpContext.Features.Get<IForwarderErrorFeature>(); var exception = errorFeature?.Exception; } } }
步骤3:在Index视图中嵌入iframe
直接在Index.cshtml中添加指向代理路由的iframe:
@{ ViewData["Title"] = "Proxy Page"; } <iframe src="@ViewData["ProxyUrl"]" width="100%" height="800px" frameborder="0"></iframe>
2. 解决Cookie/Session被设置到自身站点的问题
方法1:通过YARP转换修改Cookie属性
在Program.cs中添加Cookie转换逻辑,将目标站点的Cookie属性修正为对应域名:
builder.Services.AddReverseProxy() .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")) .AddTransforms<CookieTransformProvider>(); // 自定义Cookie转换类 public class CookieTransformProvider : ITransformProvider { public void Apply(TransformBuilderContext context) { context.AddResponseTransform(async context => { if (context.HttpContext.Response.Headers.TryGetValue(HeaderNames.SetCookie, out var cookies)) { var modifiedCookies = new List<string>(); foreach (var cookie in cookies) { // 修改Cookie的Domain为目标站点域名,添加SameSite隔离属性 var modifiedCookie = cookie .Replace("Domain=", "Domain=target.example.com; ") + "; SameSite=None; Secure"; modifiedCookies.Add(modifiedCookie); } context.HttpContext.Response.Headers.SetCookie = modifiedCookies; } }); } }
方法2:使用iframe sandbox属性隔离Cookie
在iframe标签中添加sandbox属性,让浏览器隔离iframe与主站的Cookie环境:
<iframe src="@ViewData["ProxyUrl"]" width="100%" height="800px" frameborder="0" sandbox="allow-same-origin allow-scripts allow-forms"></iframe>
注意:sandbox会限制iframe的部分权限,需根据业务需求调整允许的权限项。
内容的提问来源于stack exchange,提问作者user3404171
相关产品推荐
相关产品推荐

