我创建了一个web API
,其中CRUD
操作执行。现在我想实时测试它,所以我决定通过遵循this教程来制作控制台应用程序。本教程提供了在运行应用程序时自己创建产品并获取,更新和删除它的代码的代码。但我想使用用户输入。我成功地创造了产品。不过,虽然得到它我面临的一个问题,看我的代码无法在控制台应用程序中使用GET方法
类
class Product
{
[Key]
public string Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public string Category { get; set; }
}
控制台
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;
client.BaseAddress = new Uri("http://localhost:7361/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
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 };
var 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:
Environment.Exit(0);
break;
}
}
在case 2
在product = await GetProductAsync(url.PathAndQuery);
,我无法使用url
变量它说Use of unassigned local variable 'url'
。
另外我不能声明var
外面,因为它不会被初始化为任何人。
我试图将类型从var
更改为string
但仍无法执行任务。
任何帮助将高度赞赏
如果您启动了控制台应用程序并立即选择了选项2,您会发生什么?它从哪里得到产品? –
您有一个简单的范围界定问题,与制作网络请求无关。你的代码会更干净,更容易推理,如果它是一个while循环而不是带有'goto'的开关。 – Crowcoder
@KirkLarkin当我选择选项2,然后没有任何反应,按下输入按钮后,应用程序退出 – faisal1208