We are using RestSharp to upload a base64 encoded file. The API requires a request format that looks like the following, but we are unable to produce this format using RestSharp. I think there must be a way?
FORMAT 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--
Using RestSharp, we are only able to create a request that looks like...
FORMAT 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=
For the API we are hitting, this works fine unless the "attachment" parameter is a larger file. We can manually compose/submit a request for larger files if we use FORMAT 1. FORMAT 2 fails, but that is all we can get out of RestSharp.
Here is the code we are using.
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);
How is this code changed to produce a request in FORMAT 1?
RestSharp
can build a proper multipart/form-data
request automatically, so you don't need to specify Content-Type
header manually and you can remove multipart/form-data
and ParameterType.RequestBody
from parameters. Then you just need to set AlwaysMultipartFormData
property to true
so it will generate proper headers and body for you
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;