0

I need to post data another API. That API build with DotNet Core.

Model that I have data and same model I need to post another API.

public class SaveViewModel
{
    public string Description { get; set; }
    public List<SaveAttachment> Attachments { get; set; }
}

public class SaveAttachment
{
    public string AttachCode { get; set; }
    public IFormFile File { get; set; }
}

I try as below but that way I only sent list of file but I need to send List<SaveAttachment>.

MultipartFormDataContent multiContent = new MultipartFormDataContent();  
multiContent.Add(new StringContent(model.Description), "Description");

if (model.Attachments != null)
{
    foreach (var item in model.Attachments)
    {
        multiContent.Add(new StreamContent(item.File.OpenReadStream())
        {
            Headers = { ContentLength = item.File.Length, ContentType = new MediaTypeHeaderValue(item.File.ContentType) }
        }, "Attachments", item.File.FileName);
    }
}
Sender
  • 6,660
  • 12
  • 47
  • 66
  • Why not serializing the whole object and passing in `multiContent.Add(new StringContent(JsonConvert.Serialize(model)), "SaveModel");` – Jamshaid K. Dec 11 '20 at 06:07
  • With out file it works. But I need to post file. For file you need to use `MultipartFormDataContent` – Sender Dec 11 '20 at 06:20
  • For the file, you might want to get the bytes of the file and send those bytes. See: https://stackoverflow.com/a/19983672/4308286 – Jamshaid K. Dec 11 '20 at 06:24
  • That is different things for that you need to change existing API, But real implement is using `MultipartFormDataContent`. @JamshaidK. I saw this comment URL and Many time before I pass file data that way but that either single file or List of files, but my issue how we can do with class `List` structure. – Sender Dec 11 '20 at 06:26
  • Are you posting to a 3rd party API or an API where you have control of the code? – Todd Menier Dec 11 '20 at 17:00
  • @ToddMenier 3rd party API I don't have control. – Sender Dec 14 '20 at 14:43

0 Answers0