Reputation: 4319
I'm trying to mimick a c# class definition taken in on the body of a webapi call in powershell so I can call a rest method with that object represented as json. An example of the structure of json I'm trying to achieve would be:
'{
"Name" : "Test" ,
"Items" : [{"Key" : "Test", "Value" : "t2"},{"Key" : "Test2", "Value" : "t3"}]
}'
This json works when set to the body of the rest call in postman, if I call the powershell invokerest-method with it all fields are simply null on the webapi end.
Here is my current attempt at this in powershell, note, Items is effectively a list of key value pair objects. Using the below code I just get 1 item in items, with a null name and value.
$spec = @{
Name = 'Test'
Items = ,{Name = 'Test', Value = 't2'}, {Name = 'Test2', Value = 't3'}
}
invoke-restmethod $someurl -Method:POST -body $spec | Write-Host
I'm fairly sure I'm missing something important with the array declaration for items on the powershell object.
Here is the rest method:
[HttpPost]
[Route("addorupdateitem")]
public void Add([FromBody] ItemConfigurationDto itemconfig)
{
var serializeObject = Newtonsoft.Json.JsonConvert.SerializeObject(context);
Debug.WriteLine(serializeObject);
}
and the objects
public class ItemConfigurationDto
{
public string Name { get; set; }
public List<Item> Items { get; set; } = new List<Item>();
}
public class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
Upvotes: 2
Views: 2132
Reputation: 4319
Fixed the issue. I had to set -ContentType 'application/json' and convert the object to json before adding it to the body.
Upvotes: 2