2017-03-05 81 views
0

我得到一個錯誤「不能從int轉換爲system.net.http.httpcompletionoption。HTTP錯誤完成

我是新來構建Web API,以及我只是想創建一個簡單的GET請求,它接受一個int id並轉到我的API中的get方法,該方法接受一個int並返回具有該id的產品。我將在下面發佈我的代碼,以及我在哪裏得到錯誤。

public ActionResult Details(int id) 
    { 
     Contact contact = new Contact(); 
     HttpClient client = new HttpClient(); 
     client.BaseAddress = new Uri("http://localhost:56194/"); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 
//Im getting error on line below right after client.GetAsync on the id after the uri 
     HttpResponseMessage response = client.GetAsync("api/contacts", id).Result; 
     if (response.IsSuccessStatusCode) 
     { 
      contact = response.Content.ReadAsAsync<Contact>().Result; 
     } 
     return View(contact); 

    } 

我的API方法目前低於

[ResponseType(typeof(contact))] 
    public IHttpActionResult Getcontact(int id) 
    { 
     contact contact = db.contacts.Find(id); 
     if (contact == null) 
     { 
      return NotFound(); 
     } 

     return Ok(contact); 
    } 

謝謝,我希望得到任何幫助不能找到很多關於谷歌有關的人遇到這個錯誤。

回答

0

如果你看看GetAsync的文檔,你應該在第二個參數中傳遞枚舉值,即HttpCompletionOption enum

所以,如果你想使用int,那麼你應該把它投到HttpCompletionOption。 您的代碼應該是:

 HttpResponseMessage response = client.GetAsync("api/contacts", 
               (HttpCompletionOption)id).Result; 

看來你的id是讓接觸,那麼你應該做的:

HttpResponseMessage response = client.GetAsync("api/contacts/" + id, 
              HttpCompletionOption.ResponseContentRead).Result;