Flurl multipart/form-data Unexpected End of Stream

This is a solution to an IOException "Unexpected end of Stream" when using Flurl to post multipart/form-data.

I recently was attempting to upload multipart/form-data using Flurl and ASPNET Core server was throwing this exception: "System.IO.IOException: Unexpected end of Stream, the content may have already been read by another component.".

TLDR

The root cause of this error is that the boundary value was wrapped in double quotes in the media type header but was not wrapped in quotes in the request body. The solution was just to trim the double quotes from the boundary value.

Deeper Dive

Here's the content-type header value from the http request. Notice how the GUID is wrapped in double quotes.

multipart/form-data; boundary=\"8fee35ce-e3f2-4589-9992-d4871575effa\"
The HTTP Request's Content-Type Header Value

Here's the gist of the request body (binary data omitted). Notice how the same GUIDs lack the double quotes.

--8fee35ce-e3f2-4589-9992-d4871575effa
Content-Type: application/octet-stream
Content-Disposition: form-data; name=file; filename=foo.jpg; filename*=utf-8''foo.jpg

BINARY DATA
--8fee35ce-e3f2-4589-9992-d4871575effa--
The HTTP Request Body

I was using Microsoft.AspNetCore.WebUtilities.MultipartReader to read the http request body. Like so:

var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
The MultipartReader declaration

The exception was being thrown on this line directly below:

var section = await reader.ReadNextSectionAsync(cancellationToken);
The line throwing the IOException

The solution was to trim the double quotes from the boundary:

var reader = new MultipartReader(mediaTypeHeader.Boundary.Value.Trim('"'), request.Body);
The fixed MultipartReader declaration