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

C# 无法在控制台应用程序中使用GET方法,c#,visual-studio,asp.net-web-api2,console-application,dotnet-httpclient,C#,Visual Studio,Asp.net Web Api2,Console Application,Dotnet Httpclient,我创建了一个webapi,其中执行CRUD操作。现在我想在实时的基础上测试它,所以我决定通过以下教程制作一个控制台应用程序。本教程提供了一段代码,在该代码中,运行应用程序时,用户可以自行创建产品,并获取、更新和删除产品。但是我想使用用户输入。我成功地创建了产品。但是,当我得到它时,我面临一个问题,请参阅我的代码 课程 class Product { [Key] public string Id { get; set; } [Required]

我创建了一个
webapi
,其中执行
CRUD
操作。现在我想在实时的基础上测试它,所以我决定通过以下教程制作一个控制台应用程序。本教程提供了一段代码,在该代码中,运行应用程序时,用户可以自行创建产品,并获取、更新和删除产品。但是我想使用用户输入。我成功地创建了产品。但是,当我得到它时,我面临一个问题,请参阅我的代码

课程

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;
            }
}
statichttpclient=newhttpclient();
静态无效显示产品(产品)
{
Console.WriteLine($“Name:{product.Name}\tPrice:{product.Price}\t类别:{product.Category}”);
}
静态异步任务CreateProductAsync(产品)
{
HttpResponseMessage response=wait client.postsjsonAsync(“api/product/”,product);
response.EnsureSuccessStatusCode();
//返回所创建资源的URI。
返回response.Headers.Location;
}
静态异步任务GetProductAsync(字符串路径)
{
Product=null;
HttpResponseMessage response=wait client.GetAsync(路径);
if(响应。IsSuccessStatusCode)
{
product=wait response.Content.ReadAsAsync();
}
退货产品;
}
静态异步任务RunAsync()
{
INTA;
十进制价格=0;
字符串名称=null,类别=null;
字符选项;
client.BaseAddress=新Uri(“http://localhost:7361/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
尝试
{
标签:
Console.Write(“1.创建产品\n”);
Console.Write(“2.查看产品\n”);
控制台。写入(“3.更新产品\n”);
控制台。写入(“4.删除产品\n”);
Console.Write(“5.Exit\n”);
Console.WriteLine(\n输入您的选择:);
a=Convert.ToInt32(Console.ReadLine());
开关(a)
{
案例1:
Console.WriteLine(“输入产品名称:”);
name=Convert.ToString(Console.ReadLine());
Console.WriteLine(\n输入产品价格:);
price=Convert.ToDecimal(Console.ReadLine());
Console.WriteLine(\n输入产品类别:);
category=Convert.ToString(Console.ReadLine());
//创建新产品
产品产品=新产品{名称=名称,价格=价格,类别=类别};
var url=await CreateProductAsync(产品);
WriteLine($”创建于{url});
Console.WriteLine(“要创建更多产品吗?(y/n):”;
option=Convert.ToChar(Console.ReadLine());
如果(选项='y'| |选项=='y')
{
Console.Clear();
转到案例1;
}
else if(选项=='n'| |选项=='n')
{
Console.Clear();
后藤标签;
}
打破
案例2:
//获取产品
product=wait-GetProductAsync(url.PathAndQuery);
展示产品(产品);
打破
//案例3:。。。
//案例4:。。。
案例5:
环境。退出(0);
打破
}
}
case2
product=wait-GetProductAsync(url.PathAndQuery);
中,我无法使用
url
变量,因为它表示
使用未分配的局部变量“url”

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

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


非常感谢您提供的任何帮助

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

您试图在
案例2:
中使用变量
url
,尽管该变量不在本案例的范围内。您似乎在
案例1:
中声明了
url
,从技术上讲,此变量不能通过关闭案例1的
break
语句进行访问

后退一步,快速阅读


快速修复方法是在
开关()之前删除
uriurl
,因此它可以在交换机的所有机箱中访问。只需确保为它提供一个初始值或添加一个
默认值:
语句,并在那里初始化它,然后再在代码中进一步使用它。

如果启动控制台应用程序并立即选择选项2,您会期望发生什么?它会在哪里您的产品是否来自?您有一个简单的范围问题,与web请求无关。如果您的代码是while循环,而不是带有
goto
s的开关,那么您的代码将更干净、更容易推理。当我选择选项2时,则什么都不会发生,按下enter按钮后,应用程序将运行exits@Crowcoder我不得不告诉妈妈ke user option,这就是我使用switch的原因。我在switch外部声明了
Uri url
。在运行应用程序后,当我选择
option 2
时,我得到了这个错误
没有MediaTypeFormatter可用于从媒体类型为“text/html”的内容中读取“Product”类型的对象。3