添加异步

时间:2019-04-25 00:05:38

标签: c# asynchronous httpwebrequest httpwebresponse system.net

因此,我一直在摆弄C#中的Web响应和请求,并且在尝试运行该程序时遇到了问题。我拥有的代码行之一:

var response = await httpClient.SendAsync(request);

方法制作中需要异步

private static void Main(string[] args)

进入

private static async Task Main(string[] args)

看起来没有错误,但是在构建过程中,我收到了错误消息:

  

程序不包含适用于入口点的静态“ Main”方法。

这是我的代码

private static async Task Main(string[] args)
        {

            try
            {
                /*HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://billing.roblox.com/v1/gamecard/redeem");
                            request.Method = "POST";
                            request.ContentType = "application/json";
                            request.Accept = "application/json";
                            JsonExtensionDataAttribute data = new JsonExtensionDataAttribute();
                            data = '3335996838'*/
                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://billing.roblox.com/v1/gamecard/redeem"))
                    {
                        request.Headers.TryAddWithoutValidation("Accept", "application/json");

                        request.Content = new StringContent("3335996838", Encoding.UTF8, "application/json");

                        var response = await httpClient.SendAsync(request);

                        Console.WriteLine(request.Content);
                        Console.ReadLine();
                    }
                }
            }
            catch (WebException ex)
            {
                string content;
                using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                {
                    content = reader.ReadToEnd();
                    Console.WriteLine(content);
                    Console.ReadLine();
                }
            }
        }

请帮助我!

2 个答案:

答案 0 :(得分:0)

我怀疑自white works out of the box for new projects on Visual Studio 2019起,您仍在使用Visual Studio 2017。

要允许async Main,您需要指定async Task Main作为您的语言版本。 (构建->高级->语言版本)。 LatestMinor是C#7.1语言功能,在VS2017下,新项目默认为C#7.0。

答案 1 :(得分:-1)

main方法必须使用void返回类型。 您可以返回void main并更改以下行:

  var response = await httpClient.SendAsync(request);

var response = httpClient.SendAsync(request).Result;

.Result正在获取任务的结果值。