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