PowerShell/test/tools/WebListener/Controllers/MultipartController.cs
Mark Kraus fd3a003765 Add Multipart Support to Web Cmdlets (#4782)
Partially implements  #2112
- Adds `System.Net.Http.MultipartFormDataContent` as a possible type for `-Body`
- Adds `/Multipart/` test to WebListener 

This allows for the user to create their own `Http.MultipartFormDataContent` object and submit it. Since `multipart/form-data` submissions are highly flexible, adding direct support for it to the CmdLets may over-complicate the command parameters and a limited implementation would not address the broad scope of use cases. This at least allows the user to submit multipart forms using the Web Cmdlets and not have to manage their own `HttpClient`. Once this is introduced, limited multipart implementations can be expanded to use the code in this PR.
2017-09-12 09:41:36 -07:00

89 lines
2.9 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using mvc.Models;
namespace mvc.Controllers
{
public class MultipartController : Controller
{
private IHostingEnvironment _environment;
public MultipartController(IHostingEnvironment environment)
{
_environment = environment;
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(IFormCollection collection)
{
if (!Request.HasFormContentType)
{
Response.StatusCode = 415;
Hashtable error = new Hashtable {{"error","Unsupported media type"}};
return Json(error);
}
List<Hashtable> fileList = new List<Hashtable>();
foreach (var file in collection.Files)
{
string result = string.Empty;
if (file.Length > 0)
{
using (var reader = new StreamReader(file.OpenReadStream()))
{
result = reader.ReadToEnd();
}
}
Hashtable fileHash = new Hashtable
{
{"ContentDisposition" , file.ContentDisposition},
{"ContentType" , file.ContentType},
{"FileName" , file.FileName},
{"Length" , file.Length},
{"Name" , file.Name},
{"Content" , result},
{"Headers" , file.Headers}
};
fileList.Add(fileHash);
}
Hashtable itemsHash = new Hashtable();
foreach (var key in collection.Keys)
{
itemsHash.Add(key,collection[key]);
}
MediaTypeHeaderValue mediaContentType = MediaTypeHeaderValue.Parse(Request.ContentType);
Hashtable headers = new Hashtable();
foreach (var key in Request.Headers.Keys)
{
headers.Add(key, String.Join(Constants.HeaderSeparator, Request.Headers[key]));
}
Hashtable output = new Hashtable
{
{"Files" , fileList},
{"Items" , itemsHash},
{"Boundary", HeaderUtilities.RemoveQuotes(mediaContentType.Boundary).Value},
{"Headers" , headers}
};
return Json(output);
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}