29

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...

5
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Apr 2, 2014 at 0:29
  • Sorry, bout that! Just read that article, thanks for the edit. Commented Apr 2, 2014 at 0:31
  • I'm also in search of it's answer. @JNYRanger did you found the answer yet..? please let me know if you have solution. Thanks in advance. Commented Aug 26, 2014 at 14:53
  • @KevalLangalia No. I ended up dropping RestSharp and creating my own REST client using the standard HttpWebRequest class and JSON.NET Commented Aug 26, 2014 at 20:13
  • for the future visitors, this issue has been fixed on RestSharp. discussion thread: github.com/restsharp/RestSharp/issues/524 Commented Jun 21, 2016 at 15:22

2 Answers 2

22

So I am doing this by working around a problem with using the AddBody method which automatically kills the multi part form images and will not send them. You must use add parameter instead.

To solve this problem you may have to do a little work on both sides of the communication.

To send the message from the client you do the following:

new RestRequest("<Your URI>");
request.AddParameter("request", tokenRequest.ToJson());
request.AddFile("front", frontImage.CopyTo, "front");
request.AddFile("back", backImage.CopyTo, "back");
request.AddHeader("Content-Type", "multipart/form-data");

On my web service side, I accept the json as the argument to the method and manually obtain a reference to the file streams:

public JsonResult MyService(StoreImageRequest request)
{
    var frontImage = HttpContext.Request.Files["front"].InputStream;
    var backImage = HttpContext.Request.Files["front"].InputStream;
}
Sign up to request clarification or add additional context in comments.

3 Comments

does this code work for you @C Tierney. I wanna upload a file along with some parameters but i cant get it working. Am always getting response with status code 0. {"The underlying connection was closed: An unexpected error occurred on a send."}
tokenRequest is of course undefined and throw an exception for same... is the first line supposed to be 'var tokenRequest = ' followed by the line? Or, is that line supposed to be 'var request = ', I'm having this problem/exception and this code snippet is useless to me.
token was my json object i wanted to pass with it, back image and front image are also code variables above that. We tokenize check images, the tokenRequest is our object we wanted to pass with the files to build the data set to associate with the securely stored check images. Sorry that I didn't make that more clear.
4

Multi-part request with JSON body + File parts

If your server can process a multi-part with JSON body and Files parts, then

Client code:

        var req = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST);

        req.RequestFormat = DataFormat.Json;
        req.AddBody(doc);

        req.AddFileBytes("TestImage", Properties.Resources.TestImage, "TestImage.jpg");

        req.AddHeader("apikey", "MY-API-KEY");
        var resp = restClient.Execute<ApiResult>(req);

Server code:

At the server side such multi-part request should be processed as:

    [HttpPost]
    public JsonResult UploadDoc()
    {
        // This is multipart request. So we should get JSON from http form part:
        MyDocModel doc = JsonConvert.DeserializeObject<MyDocModel>(Request.Form[0]);
        
        foreach (string fileName in request.Files)
        {
            HttpPostedFileBase file = request.Files[fileName];
        }

1 Comment

The previous answer solves the need declared in the subject by using a workaround tokenRequest.ToJson(). This answer proposes using req.RequestFormat = DataFormat.Json that works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.