0

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.

1
  • It looks like it's a bug in dotnet. When the code runs under dotnet framework 4.8, it works as expected. On dotnet 8, it fails Commented Mar 14 at 16:19

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.