From 433ef2040ae4fbea1960b77320814e0ffc311d12 Mon Sep 17 00:00:00 2001 From: Jeremy Benscoter Date: Mon, 18 Sep 2023 15:16:30 -0400 Subject: [PATCH] Update Helpers.cs Update ToHttpContent helper function to copy files to MemoryStreams to prevent InvalidOperationException from occuring when multiple files are sent in a request --- src/Core/Helpers/Helpers.cs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/Core/Helpers/Helpers.cs b/src/Core/Helpers/Helpers.cs index 1139658..c0eaec5 100644 --- a/src/Core/Helpers/Helpers.cs +++ b/src/Core/Helpers/Helpers.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using System.Web; using Microsoft.AspNetCore.Http; +using System.IO; namespace AspNetCore.Proxy { @@ -106,16 +107,25 @@ internal static HttpContent ToHttpContent(this IFormCollection collection, HttpR } foreach (var file in collection.Files) { - var content = new StreamContent(file.OpenReadStream()); - foreach (var header in file.Headers.Where(h => !h.Key.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase))) - content.Headers.TryAddWithoutValidation(header.Key, (IEnumerable)header.Value); + var ms = new MemoryStream(); - // Force content-disposition header to use raw string to ensure UTF-8 is well encoded. - content.Headers.TryAddWithoutValidation("Content-Disposition", - new string(Encoding.UTF8.GetBytes($"form-data; name=\"{file.Name}\"; filename=\"{file.FileName}\""). - Select(b => (char)b).ToArray())); + using (var fs = file.OpenReadStream()) + { + //copy content to a new stream to prevent exception + //when multiple files are included in the initial request + fs.CopyTo(ms); + var content = new StreamContent(ms); - multipart.Add(content); + foreach (var header in file.Headers.Where(h => !h.Key.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase))) + content.Headers.TryAddWithoutValidation(header.Key, (IEnumerable)header.Value); + + // Force content-disposition header to use raw string to ensure UTF-8 is well encoded. + content.Headers.TryAddWithoutValidation("Content-Disposition", + new string(Encoding.UTF8.GetBytes($"form-data; name=\"{file.Name}\"; filename=\"{file.FileName}\""). + Select(b => (char)b).ToArray())); + + multipart.Add(content); + } } return multipart; }