[英]How to create simple IIS site to redirect all calls to another service?
我已经在Delphi中编写了REST API服务,该服务作为其自己的独立服务运行。 我也有IIS在端口80
上托管一些站点。 我也想将端口80
用于我的REST API,但是由于我已经在IIS中使用它,因此不得不使用其他端口。
我想解决的方法是在IIS中创建一个非常简单的站点(最好使用ASP.NET/C#),该站点将所有传入的HTTP请求重定向到在其他端口上运行的该其他服务。 这将使我能够利用在IIS中同一端口下绑定多个站点的优势。 我不想执行原义的“重定向”,而只是将请求复制到所需的服务器,然后进行响应-就像用户正在连接到原始REST服务器一样。 仅,而不必使用非标准端口。 客户端的URL不应更改(如您通常在HTTP重定向中看到的那样)。
本质上,如果用户发出这样的请求:
http://api.mydomain.com/SomeReq?some=query
它将转过来向真实服务器发出相应的请求,并保留整个URI-只是一个不同的端口号:
http://api.mydomain.com:8664/SomeReq?some=query
我该怎么做?
使用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/*
动词。
显然,如果您要将整个Web服务器变成代理并侦听:80/*
则可以摆脱在示例中使用的/proxy
前缀。
话虽如此,这只是一个概念验证代理服务器。 在实际的生产系统中,我会将这项任务卸载到专门为此目的而设计的功能HAProxy
前端负载均衡器(例如nginx
或HAProxy
中。 然后,您的IIS和Delphi应用程序都可以侦听任意端口,并将您的nginx配置为侦听端口80,并根据某些模式将流量转发到后端节点。 使用负载均衡器还有其他好处,就像您有多个后端节点一样,它将在它们之间分配负载,还使您可以在不停机的情况下对应用程序进行更新(因为您可以完全控制哪个节点位于其中负载平衡器池)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.