0

I'm trying to get something similar to this answer and this answer to work where I utilize Invoke-RestMethod to post some variables and a list of files to a controller. However, AFAICT I've correctly adapted the powershell bits, but the MVC controller doesn't like it.

Here's a repro. In a fresh, new MVC 5 application, I've added this method to the Home controller:

[HttpPost]
public ActionResult Upload(string description, HttpPostedFileBase[] files)
{
    if (string.IsNullOrWhiteSpace(description)) return Content("Description is required");
    if (files == null || !files.Any()) return Content("At least one file required");
    return Content("Dummy success.");
}

I try to talk to it like this:

$baseUri = "http://localhost:62441"

$body = @{
    "description" = "Test upload."
    "files" = Get-Content("MyStuff.dll") -Raw
}

Invoke-RestMethod `
    -Method Post `
    -Uri "$baseUri/home/upload" `
    -Body $body `
    -ContentType "multipart/form-data"

# Outputs "Description is required"

Which is a remix of aforementioned (and various other) answers. However, if I run the script the MVC side gets an empty description, and an empty list of files.

Is something in the MVC action causing this? How could I adjust the code (preferably the powershell bit) to make this work?

PS. I've since found this answer that explains how to custom-build the Body, but that's quite a bit of work I'd love to avoid, and given from the answers mentioned in the beginning I suspect that it should actually be possible?

Community
  • 1
  • 1
Jeroen
  • 53,290
  • 30
  • 172
  • 279

1 Answers1

0

I welcome anyone with a competing answer, but until that moment I'll claim that this is not (easily) possible with the plain Invoke-RestMethod cmdlet, at least not without wrapping it in another function that builds up the multipart form.

This basically means using my answer to the question I mentioned above, when using that cmdlet you can just call it like this:

$url ="http://localhost:62441/home/upload"
$form = @{ description = "Test upload." }
Get-ChildItem .\MyStuff.dll | Send-MultiPartFormToApi $url $form
Community
  • 1
  • 1
Jeroen
  • 53,290
  • 30
  • 172
  • 279