我創建了一個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