0

Is there a way to send an object and a file in the same HTTP request in ASP.NET WebAPI and C#?

I have a controller method which should receive such a request, which I generate on back-end (currently using RestSharp, but don't have to). This is the code so far, but it is a standard request, without file added:

var url = _apiUrl + "api/whatever";
var restRequest = new RestRequest(url, Method.POST, DataFormat.Json);
restRequest.AddHeader("authorization", "Bearer " + token);

var requestData = new MyData
{
    //...
};

restRequest.AddParameter("application/json", ParameterType.RequestBody);
restRequest.AddJsonBody(JsonConvert.SerializeObject(labelModel, Formatting.Indented));

// add file somehow?

var apiResult = _restClient.Post(restRequest);

The point of this is that requestData contains instructions on what to do with the file.

[SOLUTION]

I made it work by using multipart/formdata as Panagiotis Kanavos suggested, by changing the request like so:

restRequest.AddParameter(new Parameter("data", JsonConvert.SerializeObject(requestData, Formatting.Indented), ParameterType.RequestBody));
var file = File.ReadAllBytes(@"C:\test.png");
restRequest.AddFile("file", file, "test.png");
var apiResult = _restClient.Post(restRequest);
dzenesiz
  • 1,388
  • 4
  • 27
  • 58

0 Answers0