【问题标题】:GET all products by using id field使用 id 字段获取所有产品
【发布时间】:2017-09-23 08:34:11
【问题描述】:

我有一个WEB API,它有CRUD 操作。为了测试,我创建了一个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。为此,我检查了所有与之相关的文章。但仍然找不到正确的解决方案。

任何帮助将不胜感激

【问题讨论】:

  • 我找到了几个解决方案here。请尝试一下。

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


【解决方案1】:

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

另外,做GET请求你应该在url中传递id,即如果你的api url是这样的: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}");

【讨论】:

  • 我错过了什么。
猜你喜欢
  • 1970-01-01
  • 2014-07-04
  • 2017-04-01
  • 2016-03-16
  • 2017-09-25
  • 2021-05-05
  • 1970-01-01
相关资源
最近更新 更多