我在1和2教程之后创建了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 / product / 2',但我希望像'api / product /'。该路径包含最后输入的id
。
更新2
要获取我在url
product = await GetProductAsync("http://localhost:7361/api/product");
的所有产品
但是现在运行应用程序后,我收到以下错误。
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
}]
任何帮助都将受到高度赞赏
答案 0 :(得分: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);
}
这可以帮助您解决问题。