I have a web service in a RESTful web server (java) which consumes media of type MULTIPART_FORM_DATA and produces APPLICATION_JSON. I'm working on a REST client (C#) and using this web service. I'm using RestSharp as the REST client. My code goes as follows:
RestRequest request = new RestRequest("addDelivery", Method.POST);
request.AddParameter("sessionId", this.sessionId);
request.AddParameter("deliveryTo", DeliveryTo);
request.AddParameter("deliveryName", DeliveryName);
if (fileList.Count() > 0) // If fileList is not empty
{
// Adds all the files to request
foreach (MyFile myFile in fileList)
{
request.AddFile(myFile.fileName, myFile.filePath);
}
}
It works fine as long as I provide a file(s). If a file isn't provided (fileList is empty) I'm getting HTTP Status 415 - Unsupported Media Type. I think as I'm not providing any file the Content-Type is automatically changed to some type other than multipart/form-data. But the web service consumes MULTIPART_FORM_DATA and maybe that's why getting this error. I've tried adding the following code segment but getting the same error:
request.AddHeader("Content-Type", "multipart/form-data");
Note that this action(sending request without files) can be performed successfully from other clients (java, ios)
解决方案
I think you want this:
request.AlwaysMultipartFormData = true