Search code examples
c#httpdotnet-httpclient

How to send files to C# API from a console app


I have this API function to serialize XML files to object and return it:

[HttpPost("postFile")]
public IActionResult PostFile(IFormFile request, CancellationToken requestAborted)
{
  XmlSerializer ser = new XmlSerializer(typeof(FatturaElettronicaDTO));
  Stream stream = request.OpenReadStream();

  FatturaElettronicaDTO deserialized = (FatturaElettronicaDTO)ser.Deserialize(stream);
  foreach(FatturaElettronicaBodyDTO body in deserialized.FatturaElettronicaBody)
  {
    foreach(AllegatiDTO allegato in body.Allegati)
    {
      XmlNode[] n = (XmlNode[])allegato.Attachment;

      allegato.Attachment = n[0].InnerText.Replace("\n", "");
    }
  }

  return Ok(deserialized); /*fatturaDto*/
}

and I am trying to call it from this client function passing XML files in a local folder

async Task<List<HttpResponseMessage>> PostFile()
{
    List<HttpResponseMessage> results = new List<HttpResponseMessage>();
    foreach (string file in Directory.EnumerateFiles("Fatture\\", "*.xml"))
    {
        using (var httpClient = new HttpClient())
        {
            using (var content = new MultipartFormDataContent())
            {
                var fileName = Path.GetFileName(file);
                var fileStream = File.Open(file, FileMode.Open);
                content.Add(new StreamContent(fileStream), "file", fileName);

                var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
                var result = await httpClient.SendAsync(request);
                
                results.Add(result);
            }
        }
    }

    return results;
}

but it returns always 400 bad request saying that the "request" field is required, which I fulfilled.


Solution

  • In your client-side code, you are using the field name "file" to add the file to the multipart form data content. However, in your server-side code, you are using the field name "request" to deserialize the file.

    You should change

    content.Add(new StreamContent(fileStream), "file", fileName);
    

    to

    content.Add(new StreamContent(fileStream), "request", fileName);