2015-06-18 35 views
1

我目前正在通過WebApi接收請求,並試圖將其重新發送到另一個站點。使用GET請求不能發送帶有此動詞類型的內容正文

目標是通過示例接收請求:http://localhost:9999/#q=test。然後轉發給真正的網站:(我的測試,我設置google.com)http://google.com/#q=test

我下面的代碼:

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) 
    { 
     string url = request.RequestUri.PathAndQuery; 
     UriBuilder forwardUri = new UriBuilder(_otherWebSiteBase); 
     forwardUri.Path = url; 
     if (request.Method == HttpMethod.Get) 
     { 
      //request.Method = HttpMethod.Post; 
     } 
     request.RequestUri = forwardUri.Uri; 
     request.Headers.Host = forwardUri.Host; 
     return await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);//_client is an HttpClient 
    } 

目前,我得到了一個System.Net.ProtocolViolationException其中規定: Cannot send a content-body with this verb-type.

但我的輸入請求是一個GET請求(並且應該是一個GET請求)。如果我發佈POST請求,我再也沒有例外,但谷歌表示他們不期望POST請求。

那麼爲什麼會出現這種例外?任何想法如何解決它?

回答

3

我最終通過創建初始請求的副本,並重新發送它:

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) 
{ 
    string url = request.RequestUri.PathAndQuery; 
    UriBuilder forwardUri = new UriBuilder(_otherWebSiteBase); 
    forwardUri.Path = url; 

    HttpRequestMessage newRequest = request.Clone(forwardUri.Uri.ToString()); 

    HttpResponseMessage responseMessage = await _client.SendAsync(newRequest); 
    return responseMessage; 
} 

的克隆方法如下,大多來自這個問題啓發:How to forward an HttpRequestMessage to another server

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); 
     } 
     clone.Headers.Host = new Uri(newUri).Authority; 
     return clone; 
    } 
相關問題