10
將http web api請求轉發給其他服務器的最佳方式是什麼?如何將HttpRequestMessage轉發給其他服務器
這裏就是我想:
我在那裏時,我得到一定的API請求,我想修改請求,將其轉發到另一臺服務器,並返回由第二服務器發送的響應.NET項目。
我做了以下內容:
[Route("forward/{*api}")]
public HttpResponseMessage GetRequest(HttpRequestMessage request)
{
string redirectUri = "http://productsapi.azurewebsites.net/api/products/2";
HttpRequestMessage forwardRequest = request.Clone(redirectUri);
HttpClient client = new HttpClient();
Task<HttpResponseMessage> response = client.SendAsync(forwardRequest);
Task.WaitAll(new Task[] { response });
HttpResponseMessage result = response.Result;
return result;
}
凡克隆方法被定義爲:
public static HttpRequestMessage Clone(this HttpRequestMessage req, string newUri)
{
HttpRequestMessage clone = new HttpRequestMessage(req.Method, newUri);
if (req.Method != HttpMethod.Get)
{
clone.Content = req.Content;
}
clone.Version = req.Version;
foreach (KeyValuePair<string, object> prop in req.Properties)
{
clone.Properties.Add(prop);
}
foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return clone;
}
然而,出於某種原因,而不是URL重定向到指定redirectUri我得到一個404響應,其中RequestMessage.RequestUri設置爲http://localhost:61833/api/products/2
。 (http://localhost:61833
是原始請求URI的根)。
謝謝