private async Task <IDictionary <string, object> > GetMultipartForm(MultipartReader reader) { var section = await reader.ReadNextSectionAsync(); var collection = new Dictionary <string, object>(); if (section != null) { var name = GetName("name=", section.ContentDisposition); var fileName = GetName("filename=", section.ContentDisposition); var buffer = new MemoryStream(); await section.Body.CopyToAsync(buffer); if (string.IsNullOrEmpty(fileName)) { var fields = new Dictionary <string, StringValues>(); StreamReader streamReader = new StreamReader(buffer); fields.Add(name, new StringValues(UTF8Encoding.Default.GetString(buffer.GetBuffer(), 0, (int)buffer.Length))); collection.Add(name, fields); } else { var fileCollection = new HttpFormFileCollection(); StreamReader streamReader = new StreamReader(buffer); fileCollection.Add(new HttpFormFile(buffer.Length, name, fileName, buffer.GetBuffer())); collection.Add(name, fileCollection); } var formCollection = await GetMultipartForm(reader); foreach (var item in formCollection) { if (!collection.ContainsKey(item.Key)) { collection.Add(item.Key, item.Value); } } } return(collection); }
private async Task <IDictionary <string, (StringValues?Fields, HttpFormFileCollection HttpFormFileCollection)> > GetMultipartForm(MultipartReader reader) { var section = await reader.ReadNextSectionAsync(); var collection = new Dictionary <string, (StringValues?Fields, HttpFormFileCollection HttpFormFileCollection)>(); if (section != null) { var name = GetName("name=", section.ContentDisposition); var fileName = GetName("filename=", section.ContentDisposition); var buffer = new MemoryStream(); await section.Body.CopyToAsync(buffer); if (string.IsNullOrEmpty(fileName)) { var fields = new Dictionary <string, StringValues>(); StreamReader streamReader = new StreamReader(buffer); fields.Add(name, new StringValues(Encoding.Default.GetString(buffer.GetBuffer(), 0, (int)buffer.Length))); collection.Add(name, (fields[name], null)); } else { var fileCollection = new HttpFormFileCollection(); StreamReader streamReader = new StreamReader(buffer); fileCollection.Add(new HttpFormFile(buffer.Length, name, fileName, buffer.GetBuffer())); collection.Add(name, (null, fileCollection)); } var formCollection = await GetMultipartForm(reader); foreach (var item in formCollection) { if (!collection.ContainsKey(item.Key)) { collection.Add(item.Key, item.Value); } else { var(fields, httpFormFileCollection) = collection[item.Key]; if (item.Value.Fields.HasValue && !fields.HasValue) { fields = item.Value.Fields.Value; } if (httpFormFileCollection == null) { httpFormFileCollection = item.Value.HttpFormFileCollection; } else { var formFiles = item.Value.HttpFormFileCollection.Where(v => !httpFormFileCollection.Exists(p => p.FileName == v.FileName)); httpFormFileCollection.AddRange(formFiles); } collection[item.Key] = (fields, httpFormFileCollection); } } } return(collection); }