0

我有一個WEB API其中有CRUD操作。爲了測試,我創建了一個Console application。創建並獲取所有細節工作正常。現在我想通過使用id字段獲得產品。下面是我的代碼通過使用id字段獲取所有產品

static HttpClient client = new HttpClient(); 
static void ShowProduct(Product product) 
    { 

     Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCategory: {product.Category}", "\n"); 
    } 
static async Task<Product> GetProductAsyncById(string path, string id) 
    { 
     Product product = null; 
     HttpResponseMessage response = await client.GetAsync(path,id); 
     if (response.IsSuccessStatusCode) 
     { 
      product = await response.Content.ReadAsAsync<Product>(); 
     } 
     return product; 
    } 
case 3: 

        Console.WriteLine("Please enter the Product ID: "); 
        id = Convert.ToString(Console.ReadLine()); 

        // Get the product by id 
        var pr = await GetProductAsyncById("api/product/", id); 
        ShowProduct(pr); 

        break; 

client.GetAsync(path,id)的ID是給我錯誤cannot convert string to system.net.http.httpcompletionoption。爲此,我已經檢查了與之相關的所有文章。但仍然無法找到正確的解決方案。

任何幫助將高度讚賞

+0

我發現夫婦的解決方案[這裏](的https://stackoverflow.com/questions/14520762 /系統網-HTTP-httpcontent-並 - 不含有-A-定義換readasasync-一個)。請嘗試一下。 –

回答

2

因爲沒有方法GetAsync()接受第二個參數爲string你得到這個錯誤。

而且,做GET要求,你應該在URL傳遞id,也就是說,如果你的API網址是這樣的:http://domain:port/api/Products,那麼你的請求的URL應該是http://domain:port/api/Products/id其中id是你想要得到的產品的ID。

更改您的來電GetAsync()

HttpResponseMessage response = await client.GetAsync(path + "/" +id); 

,或者C#6或更高版本:

HttpResponseMessage response = await client.GetAsync(path + $"/{id}"); 
+0

那是我失蹤。 – faisal1208