使用 RestSharp 在 multipart/form-data POST 中包含文件时遇到问题

Trouble including a file in multipart/form-data POST using RestSharp

我对使用 C# 进行 Web 交互还比较陌生,我在使用 API 发出 POST 上传文件请求时遇到了一些问题。 API 只接受文件作为正文中 multipart/form-data 部分的一部分。根据其他人的建议,我一直在尝试使用 RestSharp 来执行此操作,但我似乎无法将文件本身放入 POST。来自 Postman 建议代码的代码块 - POST 起作用的地方。

我已经尝试了一些东西。该块导致 POST 在正文中使用正确的参数,但未包含任何文件。

var client = new RestClient(postURL);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", string.Format("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"upfile\"; filename=\"{0}\"\r\nContent-Type: application/xml\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", xmlPath), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
string test = response.Content.ToString();

我还尝试了 AddFile 的一些变体 - 物理文件路径、字节数组和内容类型为 application/xml 的字节数组。通过这些迭代,我能够将文件获取到 post,但是覆盖参数没有正确通过以强制文件覆盖。

var client = new RestClient(postURL);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// The different part below
request.AddFile("upfile", @xmlPath);
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
string test = response.Content.ToString();

*注意:我使用旧版本的 RestSharp (105.2.3) 与 .Net 4.0 兼容(在这种情况下坚持使用它)。

关于我在这里做错了什么有什么想法吗?

睡了一觉想通了,到头来真的很简单。所有让我陷入循环的额外 webkit 和多部分内容完全没有必要 - Postman 自动生成的代码似乎过于复杂。

var client = new RestClient(postURL);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddFile("upfile", @xmlPath);
request.AddParameter("overwrite", "true", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
string test = response.Content.ToString();