Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to have one Web API forward request to other

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?

like image 690
msk Avatar asked Jun 24 '15 11:06

msk


People also ask

How do I send a custom response in Web API?

Implementing a custom response handler in Web API. Create a new Web API project in Visual Studio and save it with the name of your choice. Now, select the Web API project you have created in the Solution Explorer Window and create a Solution Folder. Create a file named CustomResponseHandler.


1 Answers

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);
    }
like image 182
Veikedo Avatar answered Sep 18 '22 13:09

Veikedo