Post Http 调用在邮递员上工作但代码在 C# 中不工作

Post Http call working on postman but code not working in C#

我对 postman 和 c# 代码有疑问。我有两个 post 对 API 的调用,它们最终必须回调另一个 API (webhook)。

我尝试通过 Postman 发起这两个调用,并且我确实获得了正确的回调响应。我的问题是,当我使用此代码时,我没有任何回调响应,但我从我调用的服务器获得了 200 条消息。我发送的 http post 调用的所有实现都存在同样的问题,并且遇到了同样的问题。

    public static void Main(string[] args)
    {
        // first call 
        var client = new RestClient("http://xxxxxxx/emails/attachments/");
        client.Timeout = -1;
        var request = new RestRequest(Method.POST);
        request.AddHeader("Authorization",
            "Bearer theToken");
        request.AddFile("attachment",
            "C:/Users/..../pdf.pdf");
        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
        var attachmentId = response.Content;

        // second call
        client = new RestClient("http://xxxxxxx/emails/");
        client.Timeout = -1;
        request = new RestRequest(Method.POST);
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("Authorization",
            "Bearer theToken");
        request.AddParameter("application/json",
            "{\r\n  \"subject\": \"email with attachment\",\r\n  \"body\": \"Hi !!!l\r\n\",\r\n  \"received_on\": \"2021-05-24T14:07:01.5874416+02:00\",\r\n  \"author\": {\r\n    \"name\": \"dvera@mymail.fr\",\r\n    \"smtp_address\": \"\"\r\n  },\r\n  \"sender\": {\r\n    \"name\": \"dvera@mymail.fr\",\r\n    \"smtp_address\": \"\"\r\n  },\r\n  \"to\": [\r\n    {\r\n      \"name\": \"dvera@mymail.fr\",\r\n      \"smtp_address\": \"\"\r\n    }\r\n  ],\r\n  \"cc\": [\r\n    {\r\n      \"name\": \"\",\r\n      \"smtp_address\": \"\"\r\n    }\r\n  ],\r\n  \"attachments\": [\r\n       " +
            attachmentId + "\r\n  ]\r\n}\r\n", ParameterType.RequestBody);
        response = client.Execute(request);
        Console.WriteLine(response.Content);

    }
}

知道出了什么问题吗?奇怪的是,我每次拨打电话都会收到 200 条回复。

我用这段代码解决了我的问题:

using (var client = new HttpClient())
{
    using (var form = new MultipartFormDataContent())
    {
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        
       var file = File.OpenRead(attachmentPath);
       byte[] fileBytes = new byte[file.Length];
       form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "attachment", Path.GetFileName(attachmentPath));
       HttpResponseMessage response = await client.PostAsync(url, form);
       response.EnsureSuccessStatusCode();
                             
       var output = await response.Content.ReadAsStringAsync();
       PostEmailAttachmentResponse returnValue = new PostEmailAttachmentResponse();
       returnValue.Id = Int32.Parse(output);
       return returnValue;
  }
}

我以前的代码在发送附件时没有返回错误消息。服务器端出现问题,未返回错误。