使用控制台应用程序从WEB API获取所有数据
我已经在1和2教程中创建了产品web-API
。第二个教程是调用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<Product> GetProductAsync(string path)
的path
得到最后一个产品ID为 'API /产品/ 2',但我想是这样的 'API /产品/'。路径包括最后输入的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
}]
任何帮助将高度赞赏
的JSON从返回的数据API(返回所有产品)表示对象的集合,但在代码中您是tryi将其反序列化为单个产品对象。
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;
}
我建议创建新方法,因为您可能在其他地方使用旧的方法。 现在,使用新的方法,在开关的情况下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);
}
这应该可以帮助您解决问题。
我已经添加了你已经提供的代码,但它仍然给我提供了同样的错误'不能反序列化当前的JSON对象(例如{“name”:“value”})到'System'类型中。 Collections.Generic.List'1 [ClientSample.Product]',因为该类型需要一个JSON数组(例如[1,2,3])才能正确地反序列化。 要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化的类型,以使其为正常的.NET类型(例如,不是像整数这样的基本类型,也不是集合类型像一个数组或列表
您是否在情况2中调用方法'GetAllProductsAsync':? –
在调试代码时,路径又是'api/product/2'。是的,我在案例2中调用'GetALLProductAsync'。另外'列表
你从API获得的JSON响应是什么? 'GetProductAsync'只返回一个Product。 'ShowProduct'方法只有一个Product实例作为参数,并且您只将一个产品传递给'ShowProduct'参数。所以肯定它只会显示一个产品。您需要检查当您向其请求所有产品时API返回的内容。 –
@ChetanRanpariya我在'Update 2'中完成了它。 – faisal1208
您需要知道您从API获取的JSON,以了解您为什么获得'无法反序列化当前的JSON对象错误。看起来API会向您返回产品集合,并且您试图将其反序列化为单个产品。如果你分享API的JSON响应,我可以提供一些具体的解决方案。 –