方法一:这个方法很漂亮,但是,有问题,不知道什么原因,cookie偶尔会收不到,而造成验证错误,提交内容也会错误
扩展类:
public class MyTypedHandler : IProxyHandler
{
private IConfiguration _upstreamHostLookup;
public MyTypedHandler(IConfiguration upstreamHostLookup)
{
_upstreamHostLookup = upstreamHostLookup;
}
public Task<HttpResponseMessage> HandleProxyRequest(HttpContext context)
{
var host = context.Request.Host;
//var upstreamHost = _upstreamHostLookup.Find(context);
//return context
// .ForwardTo(upstreamHost)
// .AddXForwardedHeaders()
// .Send();
//context.Request.Host = new HostString("localhost");
if (host.Host == "localhost:8088")
{
return context.ForwardTo(new UpstreamHost("http://localhost")).AddXForwardedHeaders().Send();
}
else
{
return context.ForwardTo(new UpstreamHost("http://localhost:8081")).AddXForwardedHeaders().Send();
}
;
}
}
在 public void ConfigureServices(IServiceCollection services)加入:
services.AddHttpClient();
services.AddSingleton<MyTypedHandler>();
在 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 加入:
app.RunProxy<MyTypedHandler>();
方法二:稳定,暂时没发现什么问题(似乎不支持https,https出错)
在 public void ConfigureServices(IServiceCollection services) 加入:
services.AddProxy();
在 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 加入:
app.RunProxy(async context =>
{
if (context.Request.Host.Host == "localhost")
{
var response = await context
.ForwardTo("http://localhost")
.Send();
//response.Headers.Remove("MachineID");
return response;
}
else
{
var response = await context
.ForwardTo("http://localhost:8080/")
.Send();
//response.Headers.Remove("MachineID");
return response;
}
});