Best way to have one Web API forward request to other

后端 未结 2 1066
自闭症患者
自闭症患者 2021-01-30 18:31

I have a few web services running on different servers, and I want to have one web service running \"in front\" of the rest to decide which web service (server) the request shou

2条回答
  •  感情败类
    2021-01-30 19:20

    All you need to do is build a Web API DelegatingHandler like this:

    public class ProxyHandler : DelegatingHandler
    {
      protected override async System.Threading.Tasks.Task 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;
      }
    } 
    

提交回复
热议问题