2

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; }
}
2
  • 2
    Items = @{Key = 'Test'; Value = 't2'}, @{Key = 'Test2'; Value = 't3'} Commented Nov 4, 2015 at 16:11
  • @PetSerAl that one doesn't work either, I get a single item, with nulls for the name and value Commented Nov 4, 2015 at 16:16

1 Answer 1

2

Fixed the issue. I had to set -ContentType 'application/json' and convert the object to json before adding it to the body.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.