【问题标题】:using RestSharp to create a specific request type使用 RestSharp 创建特定的请求类型
【发布时间】:2021-09-05 10:20:37
【问题描述】:

我们正在使用 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,我们可以手动编写/提交更大文件的请求。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 的请求?

【问题讨论】:

    标签: c# api asp.net-core restsharp


    【解决方案1】:

    RestSharp 可以自动构建正确的multipart/form-data 请求,因此您无需手动指定Content-Type 标头,您可以从参数中删除multipart/form-dataParameterType.RequestBody。然后你只需要将AlwaysMultipartFormData 属性设置为true 这样它就会为你生成正确的标题和正文

    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;
    

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多