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

时间:2021-05-27 14:38:18

标签: c# postman restsharp

我对邮递员和 c# 代码有疑问。我有两次对 API 的 post 调用,最后必须回调到另一个 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 条回复。

1 个答案:

答案 0 :(得分:1)

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

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;
  }
}

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