使用 RestSharp 创建特定的请求类型

using RestSharp to create a specific request type

我们正在使用 RestSharp 上传 base64 编码的文件。 API 需要如下所示的请求格式,但我们无法使用 RestSharp 生成此格式。我想一定有办法吧?

格式 1

POST https://www.myapiurl.com/api/v1/add HTTP/1.1
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------330780699366863579549053
Content-Length: 522

----------------------------330780699366863579549053
Content-Disposition: form-data; name="id"

7926456167
----------------------------330780699366863579549053
Content-Disposition: form-data; name="filename"

test2.txt
----------------------------330780699366863579549053
Content-Disposition: form-data; name="description"


----------------------------330780699366863579549053
Content-Disposition: form-data; name="attachment"

dGhpcyBpcyBhIHRlc3Q=
----------------------------330780699366863579549053--

使用 RestSharp,我们只能创建一个看起来像...

格式 2

POST https://www.myapiurl.com/api/v1/add HTTP/1.1
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------330780699366863579549053
Content-Length: 83

id=7926456167&filename=SQLSearch.exe&description=&attachment=dGhpcyBpcyBhIHRlc3Q=

对于我们正在点击的API,除非“附件”参数是一个更大的文件,否则这工作正常。如果我们使用 FORMAT 1,我们可以手动 compose/submit 请求更大的文件。FORMAT 2 失败,但这就是我们可以从 RestSharp 中得到的全部。

这是我们使用的代码。

var client = new RestClient("http://myapiurl.com/api/v1/add");
var restRequest = new RestRequest(request, Method.POST);
restRequest.AddHeader("Content-Type", "multipart/form-data; boundary=--------------------------330780699366863579549053");
restRequest.AddParameter("id", "7926456167", "multipart/form-data", ParameterType.RequestBody);
restRequest.AddParameter("filename", "test2.txt", "multipart/form-data", ParameterType.RequestBody);
restRequest.AddParameter("description", "", "multipart/form-data", ParameterType.RequestBody);
restRequest.AddParameter("attachment", "dGhpcyBpcyBhIHRlc3Q=", "multipart/form-data", ParameterType.RequestBody);

如何更改此代码以生成格式 1 的请求?

RestSharp 可以自动构建适当的 multipart/form-data 请求,因此您无需手动指定 Content-Type header,您可以删除 multipart/form-dataParameterType.RequestBody 来自参数。然后你只需要将 AlwaysMultipartFormData 属性 设置为 true 这样它就会为你生成合适的 headers 和 body

var client = new RestClient("http://myapiurl.com/api/v1/add");
var restRequest = new RestRequest(request, Method.POST);
restRequest.AddParameter("id", "7926456167");
restRequest.AddParameter("filename", "test2.txt");
restRequest.AddParameter("description", "");
restRequest.AddParameter("attachment", "dGhpcyBpcyBhIHRlc3Q=");
restRequest.AlwaysMultipartFormData = true;