I'm calling a rest endpoint that accepts a multi-part form data request. One of the fields is a file and I'm using a 42k test png image.
I'm using the HttpClient to make the request like so:
using var content = new MultipartFormDataContent()
{
{ new StringContent(message.SubscriberId.ToString()), "subscriberId" },
{ new StringContent(message.TemplateName), "templateName" },
};
if (message.Attachment != null)
{
var c = new ByteArrayContent(message.Attachment.Data);
content.Add(c, "file", message.Attachment.Filename);
}
using var request = new HttpRequestMessage(HttpMethod.Post, "transactions")
{
Content = content
};
//await request.Content.LoadIntoBufferAsync();
using var msg = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
If I leave the commented out line as commented, I get a 500 internal server error back. If I uncomment that line, it works. Doing other things that spy on the request, such as calling ReadAsStringAsync()
to log the request also make it work.
I've also discovered only sending the first 12200 bytes also makes it work, but this limit is not arbitrary - some images smaller than this don't work either & I have at least one 14k image that does work without the commented out line.
The fact that some images work some don't would suggest a fault in the REST API endpoint. But the fact I can make it work by looking at the request before I send it, suggests it's not entirely that.
If the content is not examined before being sent, or the LoadIntoBufferAsync
method is not called, the content-length
header is not set. This can cause an issue in some frameworks on the receiving end, such as Node, triggering an Unexpected end of form
error.
The behaviour is also a regression from dotnet framework 4.8, which always sends the content-length header
If you encounter such an error, ensure you call LoadIntoBufferAsync
before sending the request