2015-04-28 61 views
12

我分離了一些代碼了一個網站的背後複製的代碼有問題的特定頁面後,我就PostAsJsonAsync()行代碼得到一個錯誤:的HttpClient對象方法缺少

HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user); 

這在這個using語句(添加的報頭爲好)

 using System; 
     using System.Net.Http; 
     using System.Net.Http.Headers; 
     using System.Net.Mail; 
     using System.Threading.Tasks; 
     //... 

     using (var client = new HttpClient()) 
     { 
      client.BaseAddress = new Uri("WebServiceAddress"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user); 
      if (response.IsSuccessStatusCode) 
      { 
       const string result = "Thank you for your submission."; 
       return result; 
      } 
      //... 
     } 

我得到的錯誤說

Error 4 'System.Net.Http.HttpClient' 
does not contain a definition for 'PostAsJsonAsync' and no extension 
method 'PostAsJsonAsync' accepting a first argument of type 'System.Net.Http.HttpClient' 
could be found (are you missing a using directive or an assembly reference?) 

即使它在以前的項目中工作,並從整個項目中直接複製。我忘了添加一些東西嗎?

我很感激任何關於此事的幫助。

回答

25

您必須添加以下的依賴,

System.Net.Http.Formatting.dll 

應該有在擴展 - >組裝。

您可以添加Microsoft.AspNet.WebApi.Client NuGet包

+0

賓果。只要它允許我將它標記爲答案。 –

+0

等待您的代碼正常工作;) – Abhishek

0

我有同樣的錯誤,即使在安裝了相應的NuGet包。什麼幫助我只是這個using聲明:

using System.Net.Http; 
+0

對於我來說,只有在重新安裝後才能使用該包,但是,此使用語句已在回答中,所以這不是答案。 – VMAtm

2

我寫我自己的擴展方法,因爲我相信方法僅適用於年齡較大的.NET API,並用Newtonsoft JSON序列:

// Extension method to post a JSON 
public static async Task<HttpResponseMessage> PostAsJsonAsync(this HttpClient client, string addr, object obj) 
{ 
    var response = await client.PostAsync(addr, new StringContent(
      Newtonsoft.Json.JsonConvert.SerializeObject(obj), 
      Encoding.UTF8, "application/json")); 

    return response; 
}