samedi 27 juin 2015

Submitting File and Json data to webapi from HttpClient

I want to send file and json data from HttpClient to web api server.
I cant seem to access the json in the server via the payload, only as a json var.

 public class RegulationFilesController : BaseApiController
    {
        public void PostFile(RegulationFileDto dto)
        {
            //the dto is null here
        }
    }

here is the client:

   using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
                        content.Add(new StreamContent(File.OpenRead(@"C:\\Chair.png")), "Chair", "Chair.png");
                        var parameters = new RegulationFileDto
                        {
                            ExternalAccountId = "1234",
                        };
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));

                            var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
                            resTask.Wait();
                            resTask.ContinueWith(async responseTask =>
                            {
                                var res = await responseTask.Result.Content.ReadAsStringAsync();


                            }
                                );

                    }
                }

this example will work:HttpClient Multipart Form Post in C# but only via the form-data and not payload.

Can you please suggest how to access the file and the submitted json And the file at the same request?

Thanks

Aucun commentaire:

Enregistrer un commentaire