【问题标题】:GET all data from WEB API using console application使用控制台应用程序从 WEB API 获取所有数据
【发布时间】:2017-09-23 05:29:49
【问题描述】:

我按照12 教程创建了一个web-API 产品。第二个教程是调用web-api 的控制台应用程序。现在,当我创建单个产品时,它是可以查看的。但是,当我创建多个产品时,只能查看最后一个条目。为了更好地理解,请参见下面的代码。

static HttpClient client = new HttpClient();

    static void ShowProduct(Product product)
    {

        Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCategory: {product.Category}");
    }

    static async Task<Uri> CreateProductAsync(Product product)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/product/", product);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

    static async Task<Product> GetProductAsync(string path)
    {
        Product product = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            product = await response.Content.ReadAsAsync<Product>();
        }
        return product;
    }
static async Task RunAsync()
    {
        int a;
        decimal price = 0;
        string name = null, category = null;
        char option;
        //string url;
        client.BaseAddress = new Uri("http://localhost:7361/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        Uri url = null;

        try
        {
            label:
            Console.Write("1. Create a product\n");
            Console.Write("2. View products\n");
            Console.Write("3. Update a product\n");
            Console.Write("4. Delete a product\n");
            Console.Write("5. Exit\n");

            Console.WriteLine("\nEnter your choice: ");
            a = Convert.ToInt32(Console.ReadLine());


            switch(a)
            {
                case 1:

                    Console.WriteLine("Enter name of the product: ");
                    name = Convert.ToString(Console.ReadLine());

                    Console.WriteLine("\nEnter price of the product: ");
                    price = Convert.ToDecimal(Console.ReadLine());
                    Console.WriteLine("\nEnter category of the product: ");
                    category = Convert.ToString(Console.ReadLine());

                    // Create a new product
                    Product product = new Product { Name = name, Price = price, Category = category };

                    url = await CreateProductAsync(product);
                    Console.WriteLine($"Created at {url}");

                    Console.WriteLine("Want to create more product(s)? (y/n): ");
                    option = Convert.ToChar(Console.ReadLine());

                    if(option == 'y' || option == 'Y')
                    {
                        Console.Clear();
                        goto case 1;
                    }
                    else if(option == 'n' || option == 'N')
                    {
                        Console.Clear();
                        goto label;
                    }

                    break;

                case 2:

                    // Get the product
                    product = await GetProductAsync(url.PathAndQuery);

                    ShowProduct(product);

                    break;
                   //case 3:...
                  //case 4:...
                  //case 5:...
       }

我想查看所有创建的产品。为此,我必须在创建产品时创建产品列表。但问题是我不知道在哪里做?

更新 1

在调试代码时,static async Task&lt;Product&gt; GetProductAsync(string path) path 将最后一个产品 ID 设为“api/product/2”,但我想成为那个“api/product/”。该路径包括最后输入的id

更新 2

为了获得我在product = await GetProductAsync("http://localhost:7361/api/product"); 中输入了url 的所有产品

但现在运行应用程序后,我收到以下错误。

Cannot deserialize the current JSON object (e.g. {“name”:“value”})

更新 3

通过检查Postman 中的 API 响应,以下是我得到的数据

[
{
    "Id": 1,
    "Name": "yo-yo",
    "Category": "toys",
    "Price": 45
},
{
    "Id": 2,
    "Name": "mobile",
    "Category": "electronics",
    "Price": 45000
}]

任何帮助将不胜感激

【问题讨论】:

  • 您从 API 获得的 JSON 响应是什么? GetProductAsync 只返回一个产品。 ShowProduct 方法只有一个 Product 实例作为参数,并且您只将一个产品传递给 ShowProduct 参数。因此,它肯定只会显示一种产品。当您从 API 请求所有产品时,您需要检查 API 返回的内容。
  • @ChetanRanpariya 我已经在Update 2完成了。
  • 您需要知道从 API 获得的 JSON 是什么,才能理解为什么会收到 Cannot deserialize the current JSON object 错误。看起来 API 会返回产品集合,而您正试图将其反序列化为单个产品。如果你分享 API 的 JSON 响应,我可以提供一些具体的解决方案。
  • @ChetanRanpariya 请看更新3

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


【解决方案1】:

从 API(返回所有产品)返回的 JSON 表示对象的集合,但在您的代码中,您试图将其反序列化为单个产品对象。

product = await response.Content.ReadAsAsync<Product>();

以下是您需要进行的更改才能使您的代码正常工作。 创建一个新方法,该方法将调用 GetAllProducts API 并返回产品集合,如下所示。

static async Task<List<Product>> GetAllProductsAsync(string path)
{
    List<Product> products = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        products = await response.Content.ReadAsAsync<List<Product>>();
    }
    return products;
}

我建议创建新方法,因为您可能在其他地方使用旧方法。 现在,在 switch case 2 中使用如下新方法:

case 2:
    // Get all the products
    var products = await GetAllProductsAsync(url.PathAndQuery);

    // Loop thru the products and call ShowProduct method for each product in the list.
    foreach(var product in products)
    {
         ShowProduct(product);
    }

这应该可以帮助您解决问题。

【讨论】:

  • 我已经添加了您提供的代码,但它仍然给我同样的错误 Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[ClientSample.Product]' 因为该类型需要 JSON 数组(例如 [1,2,3 ]) 正确反序列化。要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或 List)。`
  • 你是否在调用方法GetAllProductsAsync in case 2: ?
  • 在调试代码时,路径又是api/product/2。是的,我打电话给GetALLProductAsync,以防万一。List&lt;Product&gt; products = new List&lt;Product&gt;(); 计数为零
  • 为什么路径是api/product/2?因为您在case 1 中设置url 的值。您需要在 case 2 中使用正确的 url 值。在调用 GetAllProductsAsync 之前,将 url 的值设置为正确的 API url。最简单的方法是使用值api/product 调用GetAllProductsAsync
猜你喜欢
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多