RogueHippo
RogueHippo

Reputation: 59

How to set the Content-Type header for a RestRequest?

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)

Upvotes: 1

Views: 6779

Answers (2)

Ross Presser
Ross Presser

Reputation: 6265

I think you want this:

request.AlwaysMultipartFormData = true

Upvotes: 4

Itanex
Itanex

Reputation: 1714

Since RestSharp has assumed Content-Type application/x-www.form-urlencode when you don't add any files you need to apply that yourself. This should solve your problem.

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);
    }
}
else // fileList.Count() is 0 or fileList is null
{
    request.AddHeader("Content-Type", "multipart/form-data");
}

Upvotes: 0

Related Questions