Best way to have one Web API forward request to other

我的未来我决定 提交于 2019-12-03 04:35:02

问题


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 should be forwarded to based on header values.

The idea is that a client will send a request, say:

http://api.mysite.com/cars

The API at mysite.com will inspect the request, extract information from the API key (which is supplied in the headers) and redirect to the appropriate server, e.g.

http://server4.mysite.com/api/cars

Is this going to work? I'm concerned about how I will return the response (w/data) from "server4" to the client. Will the response only be returned back to the first server or will the client achieve that response?


回答1:


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;
  }
} 



回答2:


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);
    }


来源:https://stackoverflow.com/questions/31025566/best-way-to-have-one-web-api-forward-request-to-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!