I'm having issues using RestSharp for a REST API I need to use for a project I'm working on. The request I need to issue is in three parts: A header API key, a file to upload, and a bunch of data in JSON format. The API requires that the data part be sent using a form field name of "data". For some reason this is causing issues since it's naming the field "data" within the body of the request.
The code I have as is as follows:
var request = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST)
{
RequestFormat = DataFormat.Json,
AlwaysMultipartFormData = true,
JsonSerializer = new RestSharpJsonDotNetSerializer(customSerializer)
};
if (doc is DocA)
request.AddParameter("data",doc as DocA,ParameterType.RequestBody);
//request.AddBody(doc as DocA);
else
request.AddParameter("data", doc as DocB,ParameterType.RequestBody);
//request.AddBody(doc as DocB);
request.AddFile("file", doc.File.FullName);
As you can see I've attempted to use both the request.AddBody(doc)
method and the request.AddParameter(name, object, type)
method. Neither of them appear to be sending the data properly because I receive a response from the server saying required parameters are missing. Using fiddler I can see the binary data, but never the JSON data with both of these methods. I've gone through the RestSharp documentation, but I can't find anything that allows me to specify a particular "field" name as "data" for the form data body, which is what I believe is causing the issue I'm having. What am I doing wrong here?
EDIT: Upon further inspection with fiddler it appears that it's not adding my JSON data at all to the body of the HTTP request. However, with a break point right before the upload (execute command) I can see everything serialized properly within the parameter list (and file list). When inspecting the with Fiddler I see the file binary data, and then a multipart/form-data boundary, and then nothing. I would assume this is where my data is supposed to be...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…