Search code examples
asp.net-mvcasp.net-coreasp.net-core-webapimultipartform-data

Proper way to send multipart data with HttpClient


I have an api that receives form data:

[HttpPost]
[Route("sign")]
public async Task<IActionResult> SignDocument([FromForm] SignDTO signDTO)

SignDto:

public class SignDTO
{
    public IFormFile[] Files { get; set; }
    public string CertIdentifier { get; set; }
    public string Certificate { get; set; }
    public string PhoneNumber { get; set; }
    public string UserId { get; set; }
}

I'm trying to do it like this:

    SignDTO request = new SignDTO();
    request.UserId = dto.UserId;
    request.PhoneNumber = dto.Phone;
    request.Certificate = certificate.Value;
    request.CertIdentifier = certificate.Key;

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(_signUrl);

    var multipartContent = new MultipartFormDataContent();
    ByteArrayContent fileContent = new ByteArrayContent(file);
    multipartContent.Add(fileContent, "files", "files");
    multipartContent.Add(new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"), "signDTO");
    var response = await client.PostAsync("api/sign/sign", multipartContent);

but I get 400 error. I did something similar with HttpWebRequest, not sure if I'm doing it right with HttpClient. What am I doing wrong?


Solution

  • Modify:

     multipartContent.Add(new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"), "signDTO");
    

    To

    multipartContent.Add(new StringContent("CertIdentifierVal"), name: "CertIdentifier");
                multipartContent.Add(new StringContent("CertificateVal"), name: "Certificate");
                multipartContent.Add(new StringContent("PhoneNumberVal"), name: "PhoneNumber");
                multipartContent.Add(new StringContent("UserId"), name: "UserId");
    

    It works on myside:

    enter image description here

    And notice the size of files,you could check this doc related