API PUT /marketing/contacts/imports with restsharp

时间:2021-08-01 14:47:00

标签: c# restsharp sendgrid-api-v3

由于内部原因,我需要将我的 servlet 从 Java 重新编码为 c#。 我正在尝试使用带有 restsharp 的 API PUT /marketing/contacts/imports 上传 CSV 文件。 我无法正确发送文件。

代码片段 请在我的 Java 代码段下方正常工作:

    File file = new File(CSV);
    byte[] data;
    try {
        
        data = Files.readAllBytes(file.toPath());
        HttpResponse<String> response2 = Unirest.put(URLSengrid)
        
        .header(processSendgridHeader(headerFromSengrid).get(0), processSendgridHeader(headerFromSengrid).get(1))
        //("x-amz-server-side-encryption", "aws:kms")
        .body(data)
        .asString();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这里是非工作的 c# 代码:

byte[] file = System.IO.File.ReadAllBytes(testPath);

var clientSecondCall = new RestClient(URLSendgrid);
var requestSecondCall = new RestRequest(Method.PUT);
requestSecondCall.AddHeader("content -type", "application/json");
requestSecondCall.AddHeader("x-amz-server-side-encryption", "aws:kms");
requestSecondCall.AddParameter("application/json", "{"file_type":"csv","field_mappings":["e1_T","e2_T","_rf2_T","e4_T","e5_T","e12_T","e13_T","e14_T","e15_T","e16_T"]}", ParameterType.RequestBody);
requestSecondCall.AddFile("file", file, testPath);

我花了很长时间寻找答案,但没有成功。任何帮助将不胜感激

技术细节: sendgrid-csharp 版本:9.* csharp 版本:v4.0.303190

1 个答案:

答案 0 :(得分:0)

我认为问题在于您在 c# 代码中发送文件的方式。

Java 代码显然使用了请求的 Body,而 c# 代码使用的是 RestSharp。

Restsharp 以多部分形式发送文件,您的服务器可能没有资格处理。

我建议使用 HttpClient 对象:

HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Put;
request.RequestUri = new Uri( "Your Url");
request.Content = new StringContent(File.ReadAllText(yourFilePath));
request.Headers.Add("your header name", "your header value");

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