2015-09-28 43 views
2

問題是關於在C#中使用'HttpClient'。當我從服務器端迴應時,我遇到了下面的問題。 我使用 'hc.DefaultRequestHeaders.TryAddWithoutValidation(名稱,中的headMap [名稱])'HttpResponseHeaders .contains()在C#中使用HttpClient拋出異常的可能原因是什麼?

  HttpClient hc = new HttpClient(); 
      hc.Timeout = new TimeSpan(1000000000); 
      HttpContent content = new StringContent(body, Encoding.UTF8); 

      if (headMap != null && headMap.Count > 0) 
      { 
       foreach (string name in headMap.Keys) 
       { 
        hc.DefaultRequestHeaders.TryAddWithoutValidation(name, headMap[name]); 
       } 
      } 

      HttpResponseMessage responseM = hc.PostAsync(new Uri(url), content).Result; 
      endTime = DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz", new CultureInfo("en-US")); 

      HttpResponseHeaders headers = responseM.Headers; 
      IEnumerable<string> values; 
      if (headers.Contains("Content-Length")) 
      { 
       ... 
      } 

當我測試代碼爲 'headers.Contains( 「內容長度」)',它將引發 系統。例外:錯誤的標題名稱。確保請求頭與HttpRequestMessage一起使用,使用HttpResponseMessage響應頭以及使用HttpContent對象的內容頭。

我認爲異常信息缺乏用處。

你能告訴我可能的原因拋出'headers.Contains(「Content-Length」)'異常嗎?

回答

0

您可以檢查一個頭存在這樣

if(Request.Headers["Content-Length"] != null) 
相關問題