I have an WEB API
which have CRUD
operation. For testing I have created a Console application
. Create and GET all details are working fine. Now i want to get the product by using id
field. Below is my code
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;
At client.GetAsync(path,id)
the id is giving me error cannot convert string to system.net.http.httpcompletionoption
. For this I have checked all the articles related to it. But still unable to find the correct solution.
Any help would be highly appreciated
You get this error because there is no method GetAsync()
that accepts second argument as string
.
Also, doing GET
request you should pass id
in url, i.e. if your api url is something like this: http://domain:port/api/Products
, then your request url should be http://domain:port/api/Products/id
where id
is the id of product you want to get.
Change you call to GetAsync()
by:
HttpResponseMessage response = await client.GetAsync(path + "/" +id);
or if C# 6 or higher:
HttpResponseMessage response = await client.GetAsync($"{path}/{id}");