【问题标题】:how to await for PostAsync [duplicate]如何等待 PostAsync [重复]
【发布时间】:2020-05-27 11:56:33
【问题描述】:

我正在发出发布请求,但我的调试器在此行之后没有停止:

var result = await client.PostAsync(_url, data);

我的完整程序

class Program
    {
        static void Main(string[] args)
        {


            var _url = "https://test.test.test:9100/path/path";
            CheckHttpPostAsync(new { id = 123123, username = "testas" });


            async Task CheckHttpPostAsync(object payload)
            {

                    using var client = new HttpClient();
                    var json = JsonConvert.SerializeObject(payload);
                    var data = new StringContent(json, Encoding.UTF8, "application/json");
                    try
                    {
                        var result = await client.PostAsync(_url, data);
                        Console.WriteLine(result);

                    }
                    catch (Exception e)
                    {

                        Console.WriteLine(e);
                    }
            }
        }
    }

即使我正在使用等待,控制台也没有写入任何内容

post 请求在 postman 中使用相同的 JSON 可以正常工作。

编辑:添加完整代码

【问题讨论】:

  • 如何调用这个函数CheckHttpPostAsync?可以出示一下代码吗?
  • 试试var resp = await result.Content.ReadAsStringAsync();
  • 你的代码可以编译吗?使用似乎语法错误。
  • 在不再需要块的最新版本的 C# 中使用很好。
  • 执行帖子的线程中是否可能出现错误?我见过几次,在处理帖子的控制器中发生错误但它永远不会返回

标签: c# asp.net-core


【解决方案1】:

你应该 await 打电话给 CheckHttpPostAsync 并将 Main 设为 async Task Main

class Program
{
    static async Task Main(string[] args)
    {
        var _url = "https://test.test.test:9100/path/path";
        await CheckHttpPostAsync(new { id = 123123, username = "testas" });

        async Task CheckHttpPostAsync(object payload)
        {
                using var client = new HttpClient();
                var json = JsonConvert.SerializeObject(payload);
                var data = new StringContent(json, Encoding.UTF8, "application/json");
                try
                {
                    var response = await client.PostAsync(_url, data);
                    string result =  await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);

                }
                catch (Exception e)
                {

                    Console.WriteLine(e);
                }
        }
    }
}

【讨论】:

  • 更详细: CheckHttpPostAsync 被调用但没有等待 - 程序结束一旦它结束,异步就终止了 - 那么,为什么在程序结束时会写任何东西;)所以,答案是正确的 - 主要方法必须是异步和等待。
  • 为什么在 ReadAsStringAsync 上调用 Result 而不是等待它?
  • @FrancescCastells 是的,我的错,更新了
猜你喜欢
  • 2019-02-11
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 2018-04-23
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多