0

I am using PowerShell V4, with the Invoke-RestMethod command:

Add-Type @"
    using System;

    public class Person{
        public Guid Id {get;set;}
        public string Name {get;set;}
        public int Age {get;set;}
    }
"@
$person = New-Object Person
$person.Age = [int]::(Get-Random -Maximum 99 -Minimum 20)
$person.Name = [string]::("Test" + (Get-Random -Minimum 10 -Maximum 100))

Invoke-RestMethod -Uri "http://localhost:51624/api/personapi" -Method Post -Body $person

In the server side,

[HttpPost]
public IHttpActionResult Post(Person person)
{
    ...

    return Ok();
}

The person object received in server side is all properties default, for instance the Age is 0 and Name is null. If I change $person to @{Name="..."; Age=11} then it's ok.

Did I miss something, I want to hold the class definition?

Jerry Bian
  • 3,998
  • 6
  • 29
  • 54

2 Answers2

2

your casting method seems to be wrong, you should use :

$person.Age = [int](Get-Random -Maximum 99 -Minimum 20)
$person.Name = [string]("Test" + (Get-Random -Minimum 10 -Maximum 100))

Then the doc states that the body parameter of invoke-restmethod have to implement IDictionary (typically, a hash table). So you will have to convert your psobject to a hashtable. You can use the solution given by @Keith Hill for that :

$ht2 = @{}
$person.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value }
Community
  • 1
  • 1
Loïc MICHEL
  • 24,935
  • 9
  • 74
  • 103
  • No, I corrected the casting, it still cannot receive the right value for `Person` object... – Jerry Bian Sep 12 '14 at 05:46
  • Do you get the proper values if you `$person | fl` right before `Invoke-RestMethod`? – PeterK Sep 12 '14 at 05:52
  • this is actualy working : `invoke-restmethod http://test/test/ -method post -body @{age=$person.age;name=$person.name}` – Loïc MICHEL Sep 12 '14 at 05:54
  • @PeterK Yes, it output the right information as I expected. – Jerry Bian Sep 12 '14 at 06:03
  • It appears that `Invoke-RestMethod` serializes `$person` as just "Person" (that's the literal sent over the network). You might need to convert the object into a hashtable/dictionary or use `ConvertTo-Json` for a JSON-based REST service. – PeterK Sep 12 '14 at 06:18
  • @PeterK Thanks, but maybe not for `Json`, I need to convert person object to `hashtable`, do you have any idea how to convert it to `hashtable`with PowerShell build in commonds? – Jerry Bian Sep 12 '14 at 07:19
  • @Kayasax Thanks a lot, it works. My problem solved, maybe you can enhance your answer, so I can accept :) – Jerry Bian Sep 12 '14 at 07:31
0

Based on the code you posted, the issue is with [int]:: and [string]::. I suppose you wanted to cast

$person.Age = [int](Get-Random -Maximum 99 -Minimum 20)
$person.Name = [string]("Test" + (Get-Random -Minimum 10 -Maximum 100))

but you were using the double colon operator (static member accessor). Simply removing the double colons fixes the issue.

PeterK
  • 3,667
  • 2
  • 17
  • 24