无法在控制台应用程序中使用GET方法

时间:2017-09-22 20:21:32

标签: c# visual-studio asp.net-web-api2 console-application dotnet-httpclient

我创建了web API,其中执行了CRUD次操作。现在我想实时测试它,所以我决定按照this教程制作一个控制台应用程序。本教程提供了一些代码,在运行应用程序时,代码自己创建了一个产品并获取,更新和删除它。但我想使用用户输入。我成功地创造了产品。但在获得它时我遇到了问题,请参阅我的代码

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但仍无法执行任务。

任何帮助都将受到高度赞赏

1 个答案:

答案 0 :(得分:1)

分享关于如何贿赂编译器以允许使用未分配变量的提示;)

您尝试在url中使用变量case 2:,尽管该变量不存在在此案例的范围内。您似乎已在url内声明了case 1:,从技术上讲,此变量无法通过break语句结案例1进行访问。

返回一步,快速阅读variable scope within switch statement in c#

快速修复是Uri url之前的switch(),因此可以在交换机中的所有案例中访问它。只需确保给它一个初始值或添加一个default:语句并在那里初始化它,然后再在代码中使用它。