TL;DR:
The error message is extremely misleading, and does not help at all. After looking at the code though $body
looked like not a valid json. Looking even closer, PowerShell documentation mentions it does not automagically convert it even though you specified desired ContentType
:
For other request types (such as POST), the body is set as the value of the request body in the standard name=value format.
So you'd still have to convert it yourself:
Invoke-RestMethod -Method 'Post' -Uri $uri -ContentType 'application/json' -Body ($body | ConvertTo-Json);
Testing it out
I built a quick test stand to verify my assumption:
void Main()
{
var listener = new HttpListener(); // this requires Windows admin rights to run
listener.Prefixes.Add("http://*:8181/"); // this is how you define port and host the Listener will sit at: https://learn.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netcore-3.1
listener.Start();
var context = listener.GetContext();
var request = context.Request;
var response = context.Response;
var reader = new System.IO.StreamReader(request.InputStream, Encoding.UTF8);
Console.WriteLine($"Client data content type {request.ContentType}");
Console.WriteLine("Start of client data:");
Console.WriteLine(reader.ReadToEnd());// Convert the data to a string and dump it to console.
Console.WriteLine("---------------------");
// just fill the response so we can see it on the Powershell side:
response.StatusCode = 200;
var buffer = Encoding.UTF8.GetBytes("Nothing to see here");
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close(); // need this to send the response back
listener.Stop();
}
Your original code sample, came back with something like this:
Client data content type application/json
Start of client data:
Name=simPass2&Status=Complete
---------------------
but if you employ ConvertTo-Json
, the result looks way better:
Client data content type application/json
Start of client data:
{
"Name": "simPass2",
"Status": "Complete"
}
---------------------