使一个Web API转发请求到其他请求的最佳方法 [英] Best way to have one Web API forward request to other
问题描述
我有几个在不同服务器上运行的Web服务,并且我想让一个Web服务在其余服务器的前面"运行,以便根据标头值决定将请求转发到哪个Web服务(服务器)./p>
这个想法是客户端将发送一个请求,例如:
http://api.mysite.com/cars
mysite.com上的API将检查请求,从API密钥(标头中提供)中提取信息,然后重定向到适当的服务器,例如
http://server4.mysite.com/api/cars
这行得通吗?我担心如何将响应从"server4"返回到客户端.响应只会返回到第一台服务器还是客户端会实现该响应?
只需执行同一任务,除了Yazan Ati答案外,还必须添加更多行.
[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);
}
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?
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);
}
这篇关于使一个Web API转发请求到其他请求的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!