簡體   English   中英

如何將HttpRequestMessage轉發到另一台服務器

[英]How to forward an HttpRequestMessage to another server

將http web api請求轉發到另一台服務器的最佳方法是什么?

這是我正在嘗試的:

我有一個.NET項目,當我得到某些API請求時,我想修改請求,將其轉發到另一台服務器,並返回第二台服務器發送的響應。

我正在做以下事情:

[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的根)。

謝謝

您可能需要在克隆實例上顯式設置主機頭。 否則,您只是將原始請求的主機頭值復制到克隆。

即將以下行添加到克隆方法的末尾:

clone.Headers.Host = new Uri(newUri).Authority;

此外,根據您在此處嘗試實現的目標,您可能還需要處理其他問題,例如請求中的cookie域與您要轉發的新域不匹配,以及在返回的任何響應cookie上設置正確的域。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM