PostAsync not accepting MultipartFormDataContent but does accept StringContent

36 Views Asked by At

I'm trying to hit our No-Reply service from another service and add an attachment that I'm building on the fly. I can send a standard email, but when I try to add an attachment it fails. The No-Reply service has a separate endpoint for attachments. In the standard email I serialize an object and send it as string content as so:

     string emailContainer = JsonSerializer.Serialize(model);
     HttpResponseMessage response = await _http.PostAsync($"{_noReply}/Email", new StringContent(emailContainer, Encoding.UTF8, "application/json"));
     return await response.Content.ReadAsStringAsync(); 

...but when I try to add the attachment by using a multipartFormDataContent object instead, it fails.

            using (var multipartFormContent = new MultipartFormDataContent())
            {
                string emailContainer = JsonSerializer.Serialize(model);
                multipartFormContent.Add(new StringContent(emailContainer, Encoding.UTF8, "application/json"));
                byte[] byteArray = Encoding.UTF8.GetBytes(sFile);
                MemoryStream stream = new MemoryStream(byteArray);
                var fileStreamContent = new StreamContent(stream);
                fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(sMediaType);//"text/calendar");
                multipartFormContent.Add(fileStreamContent, name: "file", fileName: sFileName);

                HttpResponseMessage response = await _http.PostAsync($"{_noReply}/Email/WithAttachments", multipartFormContent);
                return await response.Content.ReadAsStringAsync();
            }

What I suspect is that the No-Reply service endpoint that is supposed to accept an attachment isn't actually configured properly to do so. Here is the code for that endpoint:

  [HttpPost("WithAttachments")]
    public async Task<IActionResult> FormSubmit([FromForm] Email email)
    {
        if (Request.Form?.Files?.Any() ?? false)
        {
            email.Attachments = Request.Form.Files
                .Where(f => f.Length > 0)
                .Select(file =>
                {
                    var a = new Attachment(file.ContentType, file.Name)
                    {
                        Stream = new MemoryStream()
                    };
                    file.OpenReadStream().CopyTo(a.Stream);
                    a.Stream.Position = 0;
                    return a;
                }).ToList();
        }
        return Accepted(await _emailService.Send(email));
    }

Is this the case or do I need to include the attachment in some different way? It looks like the endpoint wants to find the files separately from the email object, but isn't receiving the data correctly to retrieve it. Any insight is appreciated.

PS: Here is the response I get back when I try to send with an attachment.

response    {StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: {
Transfer-Encoding: chunked
Server: Microsoft-IIS/10.0
Persistent-Auth: true
X-Powered-By: ASP.NET
WWW-Authenticate: Negotiate oYG2MIGzoAMKAQChCwYJKoZIgvcSAQICooGeBIGbYIGYBgkqhkiG9xIBAgICAG+BiDCBhaADAgEFoQMCAQ+ieTB3oAMCARKicARu4Nc1uQsoWo2KNugUkItZ3RbG540l3IM/toIuGJsnF0QRaS66Z7e/yqwB0ZpglEflUBmnB7p1gDIsgtpcnzlow47pubkOBbzhTluC1XRoKXwWdkdOnAkZBRvWkGJRQXZoWdcibG1mu9Q1/R+HBxs=
Date: Mon, 19 Feb 2024 22:55:26 GMT 
}}  System.Net.Http.HttpResponseMessage
0

There are 0 best solutions below