使用id字段获取所有产品

时间:2017-09-23 08:34:12

标签: c# asp.net-web-api visual-studio-2015 console-application dotnet-httpclient

我的WEB APICRUD次操作。为了测试,我创建了一个Console application。创建和获取所有细节工作正常。现在我想使用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。为此,我检查了与之相关的所有文章。但仍然无法找到正确的解决方案。

任何帮助都将受到高度赞赏

1 个答案:

答案 0 :(得分:2)

您收到此错误,因为没有方法GetAsync()接受第二个参数string

此外,在执行GET请求时,您应该在网址中传递id,即如果您的网址是http://domain:port/api/Products,那么您的请求网址应为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}");