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

╄→гoц情女王★ 提交于 2019-12-12 10:25:32

问题


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)


回答1:


I think you want this:

request.AlwaysMultipartFormData = true



回答2:


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");
}


来源:https://stackoverflow.com/questions/25258659/how-to-set-the-content-type-header-for-a-restrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!