使用ASP.NET Web API編寫這樣的代理服務器非常簡單。所有你需要的是一個委託處理程序:
public class ProxyHandler : DelegatingHandler
{
private static HttpClient client = new HttpClient();
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// strip the /proxy portion of the path when making the request
// to the backend node because our server will be made to listen
// to :80/proxy/* (see below when registering the /proxy route)
var forwardUri = new UriBuilder(request.RequestUri.AbsoluteUri.Replace("/proxy", string.Empty));
// replace the port from 80 to the backend target port
forwardUri.Port = 8664;
request.RequestUri = forwardUri.Uri;
if (request.Method == HttpMethod.Get)
{
request.Content = null;
}
// replace the Host header when making the request to the
// backend node
request.Headers.Host = "localhost:8664";
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return response;
}
}
最後所有剩下的就是註冊此處理:
config.Routes.MapHttpRoute(
name: "Proxy",
routeTemplate: "proxy/{*path}",
handler: HttpClientFactory.CreatePipeline(
innerHandler: new HttpClientHandler(),
handlers: new DelegatingHandler[]
{
new ProxyHandler()
}
),
defaults: new { path = RouteParameter.Optional },
constraints: null
);
在這個例子中,代理將偵聽:80/proxy/*
並將其轉發給:8664/*
。
因此,如果您發送以下請求到您的Web API:
GET http://localhost:80/proxy/SomeReq?some=query HTTP/1.1
Host: localhost:80
Connection: close
將被翻譯成:
GET http://localhost:8664/SomeReq?some=query HTTP/1.1
Host: localhost:8664
Connection: close
這也將爲POST和:80/proxy/*
做其他動詞工作。
很顯然,如果你想把你的整個網絡服務器變成一個代理服務器,並且聽:80/*
那麼你可以去掉我在例子中使用的/proxy
前綴。
這就是說,這只是一個概念證明代理服務器。在真實的生產系統中,我將這項任務卸載到完全成熟的前端負載平衡器,如nginx
或HAProxy
,這些平衡器正是爲此目的而設計的。然後,您的IIS和Delphi應用程序都可以偵聽任意端口,並將您的nginx配置爲偵聽端口80,並根據某些模式將流量轉發到後端節點。使用負載平衡器還具有其他好處,就好像您擁有多個後端節點一樣,它將在它們之間分配負載,還可以讓您在沒有任何停機時間的情況下更新應用程序(因爲您可以完全控制哪個節點在負載平衡器池)。
您可以查看下面的答案:http://stackoverflow.com/a/7310936/6381169 –
@KürşatDuygulu謝謝,但我已經知道這種類型的重定向。正如我的問題所述,「我不想執行文字」重定向「,而只是將請求複製到所需的服務器。所以,如果你願意的話,有點代理人。 –