How can I name the piece of multipart/form-data given added to a request when I use the AddJsonBody()
method?
I am attempting to get past the obsolete AddParameter()
method.
Here's my code using the AddJsonBody()
method:
request.AddJsonBody(Metadata);
There's an overload that allows me to specify the Content-Type, but I just need plain old application/json
so I'm not using it. Here are the resulting relevant parts of my HTTP request as sent:
POST https://redacted/redacted HTTP/1.1
Content-Type: multipart/form-data; boundary=---------369C5A1F-30CF-450D-A5B4-2DBD93676056
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056
Content-Type: application/json
Content-Disposition: form-data; name="application/json"
{"Date":"2021-07-28T14:27:01.0718841","FurtherInfo":"This is a metadata test."}
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056
Content-Disposition: form-data; name="file"; filename="file20210728T1427010660244Z.txt"
Content-Type: text/plain
CL7~f`lz4ULMJa;]p-q!uH(-z*4iO'SHD)KYER5SI|e{3zW7^}J,%QPyD)$\K"
[...]
-----------369C5A1F-30CF-450D-A5B4-2DBD93676056--
As you can see, the "name" of the added parameter is application/json
. I want it to be "metadata" instead. So I'm using this code to get things to be sent how I want, but this code is marked as obsolete:
Parameter metadata = new Parameter("metadata", JsonConvert.SerializeObject(Metadata), "application/json", ParameterType.RequestBody);
request.AddParameter(metadata);
Using this changes the HTTP request to:
POST https://redacted/redacted HTTP/1.1
Content-Type: multipart/form-data; boundary=---------8C24DE69-C111-418A-9C29-5D9DFABA320F
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F
Content-Type: application/json
Content-Disposition: form-data; name="metadata"
{
"date": "2021-07-28T14:45:01.4650889",
"furtherInfo": "This is a metadata test."
}
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F
Content-Disposition: form-data; name="file"; filename="file20210728T1445014611849Z.txt"
Content-Type: text/plain
zoRC)Z:c]\<#/z_q,k
[...]
-----------8C24DE69-C111-418A-9C29-5D9DFABA320F--
The specific serialization doesn't matter, only that it's valid JSON and has the name metadata
.
Is there a way to use the newer AddJsonBody()
method to do this? Is manipulating the parameter name on the roadmap?
I found it!
From the class definition of RestRequest:
public IRestRequest AddParameter(string name, object value, string contentType, ParameterType type)
Instead of creating the Parameter, I can just add the parameter directly:
request.AddParameter("metadata", JsonConvert.SerializeObject(Metadata), "application/json", ParameterType.RequestBody);
And no more obsolete warning!