【问题标题】:Unable to use GET method in console application无法在控制台应用程序中使用 GET 方法
【发布时间】:2023-03-30 08:45:01
【问题描述】:

我创建了一个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 2product = await GetProductAsync(url.PathAndQuery); 中,我无法使用url 变量,因为它说Use of unassigned local variable 'url'

我也不能在它之外声明var,因为它不会被初始化给任何人。

我已尝试将类型从var 更改为string,但仍无法执行任务。

任何帮助将不胜感激

【问题讨论】:

  • 如果您启动控制台应用程序并立即选择选项 2,您希望发生什么?它从哪里得到产品?
  • 您有一个简单的范围问题,与发出 Web 请求无关。如果它是一个 while 循环而不是使用 gotos 的开关,你的代码会更清晰,更容易推理。
  • @KirkLarkin 当我选择选项 2 时没有任何反应,按下回车按钮后应用程序退出
  • @Crowcoder 我必须设置用户选项,这就是我使用 switch 的原因。

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


【解决方案1】:

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

您正在尝试在case 2: 中使用变量url,尽管该变量存在于本案例的范围内。看来您已经在 case 1: 中声明了 url,从技术上讲,这个变量不能通过 break 语句结束案例 1 访问。

后退一步,快速阅读variable scope within switch statement in c#

一个快速的解决方法是在switch() 之前删除Uri url,这样它就可以在开关的所有案例中访问。只要确保给它一个初始值或添加一个default: 语句并在那里初始化它,然后在代码中进一步使用它。

【讨论】:

  • 我已经在交换机外声明了Uri url。在我选择option 2 运行应用程序后,我收到此错误No MediaTypeFormatter is available to read an object of type 'Product' from content with media type 'text/html'.3
猜你喜欢
  • 2016-09-28
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2010-12-13
  • 2013-07-09
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多