【问题标题】:HttpresponseMessage risposta = await client.PostAsync(new Uri(uri), queryString); ends execution prematurelyHttpresponseMessage risposta = await client.PostAsync(new Uri(uri), queryString);提前结束执行
【发布时间】:2021-04-23 00:02:10
【问题描述】:

我正在尝试使用一些 c# 代码连接到 CheckPoint API,我输入所有数据(用户名和密码为 json 格式并编译 Uri),当我调用它时,它会毫无例外地结束执行

这是代码

 public async Task<HttpResponseMessage> CPAPICall()
    {
        HttpClient client = new HttpClient();
        Console.Write("username: ");
        String uname = Console.ReadLine();
        Console.Write("password: ");
        String pwd = Console.ReadLine();
        String json = "{\n" +
                      "\"user\":" + "\"" + uname + "\",\n" +
                      "\"password\"" + "\"" + pwd + "\",\n" +
                      "}";
        StringContent queryString = new StringContent(json, Encoding.UTF8, "application/json");
        Console.WriteLine("Inserisci l'IP e la porta della management CP a cui vuoi connetterti (Esempio 192.168.1.1:443, se non si inserisce la porta quella di default è 443):");
        String IpAddr = Console.ReadLine();
        String[] IpAddrEPort = new String[2];
        HttpResponseMessage risposta = new HttpResponseMessage();
        if (IpAddr.Contains(":"))
        {
            IpAddrEPort = IpAddr.Split(':');
        }
        else
        {
            IpAddrEPort[0] = IpAddr;
            IpAddrEPort[1] = "443";
        }

        String uri = "https://" + IpAddr + "/web_api/login";
        try
        {
            risposta = await client.PostAsync(new Uri(uri), queryString);
        }
        catch (HttpListenerException e)
        {
            Console.WriteLine(e);
            Console.ReadKey();
        }
        String risp = risposta.StatusCode.ToString();
        Console.WriteLine(risp);
        Console.ReadKey();
        return risposta;
    }

json 字符串管理非常糟糕,但是当我在测试时它对我有帮助。

代码到此结束risposta = await client.PostAsync(new Uri(uri), queryString);

对原因有什么建议吗?

【问题讨论】:

  • 当您说“到此结束”时,代码是否会引发任何错误/超时?如果没有,我想知道 API 是否正在做一些在返回之前等待用户反馈的事情。例如 Google OAuth 签名页面之类的。
  • 它不会抛出任何错误,一旦登录过程被确认,CheckPoint APIs 应该返回并确认一些数据并且下面的代码行应该打印这个。

标签: c# api http checkpoint


【解决方案1】:

我建议使用 Newtonsoft.Json 将您的字符串数据正确地序列化为 JSON,这会好 100%。关于过早结束,我认为调用 'CPAPICall' 的方法不是以异步方式执行的,因此请检查此方法是否是异步创建的,并在同一行的 'CPAPICall' 之前有 await 运算符。

【讨论】:

  • 我会尝试一下 json 建议,谢谢。在我发现不这样做可能会导致这个问题之后,我异步调用了 CPAPICall 方法,但没有运气(我现在仍然称它为异步)
  • 但是你在方法调用之前是否包含了'await'?
  • 是的,我这样做了 res = await CPAPICall();并且调用它的方法也被调用 await
  • 好的,我重建了异步方法链并等待调用直到 Main()。现在终于给了我一个连接错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多