我有一些Web服务在不同的服务器上运行,我希望有一个Web服务在其余的“前面”运行,以决定应该根据标头值转发请求的Web服务(服务器).
这个想法是客户会发送请求,比如说:
- http://api.mysite.com/cars
mysite.com上的API将检查请求,从API密钥(在标头中提供)中提取信息并重定向到适当的服务器,例如,
- http://server4.mysite.com/api/cars
这会起作用吗?我担心如何将响应(w / data)从“server4”返回给客户端.响应是仅返回给第一台服务器还是客户端实现响应?
解决方法
您需要做的就是构建一个Web API DelegatingHandler,如下所示:
- public class ProxyHandler : DelegatingHandler
- {
- protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,System.Threading.CancellationToken cancellationToken)
- {
- UriBuilder forwardUri = new UriBuilder(request.RequestUri);
- //strip off the proxy port and replace with an Http port
- forwardUri.Port = 80;
- //send it on to the requested URL
- request.RequestUri = forwardUri.Uri;
- HttpClient client = new HttpClient();
- var response = await client.SendAsync(request,HttpCompletionOption.ResponseHeadersRead);
- return response;
- }
- }