C# 使用id字段获取所有产品
我有一个C# 使用id字段获取所有产品,c#,asp.net-web-api,visual-studio-2015,console-application,dotnet-httpclient,C#,Asp.net Web Api,Visual Studio 2015,Console Application,Dotnet Httpclient,我有一个webapi,它有CRUD操作。为了进行测试,我创建了一个控制台应用程序。创建并获取所有详细信息工作正常。现在我想使用id字段来获取产品。下面是我的代码 static HttpClient client = new HttpClient(); static void ShowProduct(Product product) { Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCa
webapi
,它有CRUD
操作。为了进行测试,我创建了一个控制台应用程序
。创建并获取所有详细信息工作正常。现在我想使用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;
statichttpclient=newhttpclient();
静态无效显示产品(产品)
{
Console.WriteLine($“Name:{product.Name}\tPrice:{product.Price}\t类别:{product.Category}”,“\n”);
}
静态异步任务GetProductAsyncById(字符串路径,字符串id)
{
Product=null;
HttpResponseMessage response=wait client.GetAsync(路径,id);
if(响应。IsSuccessStatusCode)
{
product=wait response.Content.ReadAsAsync();
}
退货产品;
}
案例3:
Console.WriteLine(“请输入产品ID:”);
id=Convert.ToString(Console.ReadLine());
//通过id获取产品
var pr=await-GetProductAsyncById(“api/product/”,id);
展示产品(pr);
打破
在client.GetAsync(path,id)
上,id给了我错误无法将字符串转换为system.net.http.httpcompletionoption
。为此,我检查了所有与之相关的文章。但仍然无法找到正确的解决方案
如果您收到此错误,我们将非常感谢您提供的任何帮助,因为没有方法
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}");
出现此错误是因为没有方法
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}");
我找到了两种解决方案。请尝试一下。我找到了两种解决方案。请试一试。这就是我错过的。这就是我错过的。