1

I have an api in asp.net mvc:

public class UploadController : Controller
{
   ...
    public ActionResult Post(UploadModel uploadModel)

I wish to call this api from a test client, attaching files.

using (var httpClient = new HttpClient())
                {
               httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
                    var byteArrayContent = new ByteArrayContent(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
    var uploadModel = new UploadModel { Allergene = "Anders", Description = "Desc", Email = "and@juu.com" };

    var content = new StringContent(JsonConvert.SerializeObject(uploadModel), Encoding.UTF8, "application/json");

                    var multipartFormDataContent = new MultipartFormDataContent
                    {
                        {content},
                        {byteArrayContent, "\"file\"", "\"feedback.csv\""}
                    };
                    var result = httpClient.PostAsync("http://localhost:53411/Upload/Post", multipartFormDataContent).Result;
}

If I post multipartFormDataContent I don't get the attributes on my model. If I post the content, I get the attributes, but obviously not the attached file.

What am I missing?

Anders Juul
  • 2,407
  • 3
  • 34
  • 56
  • Include the body of your Post(UploadModel uploadModel) method – Fran Jul 25 '17 at 17:18
  • Side note: Make sure you aren't creating new instances of `HttpClient` for every request. I suppose its ok in a test harness but do not include in production code. [Good read on the subject](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) – maccettura Jul 25 '17 at 17:25

0 Answers0