Best way to have one Web API forward request to other

后端 未结 2 1065
自闭症患者
自闭症患者 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<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;
      }
    } 
    
    0 讨论(0)
  • 2021-01-30 19:24

    Just run into the same task and have to add some more lines in addition to Yazan Ati answer.

        [HttpPost]
        [HttpGet]
        [Route("api/TestBot/{*remaining}")]
        public Task<HttpResponseMessage> SendMessage()
        {
            const string host = "facebook.botframework.com";
            string forwardUri = $"https://{host}/api/v1/bots/billycom{Request.RequestUri.Query}";
    
            Request.Headers.Remove("Host");
            Request.RequestUri = new Uri(forwardUri);
            if (Request.Method == HttpMethod.Get)
            {
                Request.Content = null;
            }
    
            var client = new HttpClient();
            return client.SendAsync(Request, HttpCompletionOption.ResponseHeadersRead);
        }
    
    0 讨论(0)
提交回复
热议问题