Powershell 5.1-我正在使用Invoke-RestMethod
到POST
数据到端点。
API调用的主体在JSON中如下所示:
{
"ServiceKind": "Custom",
"ApplicationName": "TestApp",
"ServiceName": "TestService",
"ServiceTypeName": "TestServiceType",
"PartitionDescription": {
"PartitionScheme": "Singleton"
},
"InstanceCount": "1"
}
我在Powershell中无法正确获取语法,它似乎与PartitionDescription键有关。
这里是我所拥有的,运行时仍会引发错误:
$ServiceKind = 'Custom'
$ApplicationName = 'TestApp'
$ServiceName = 'TestService'
$ServiceTypeName = 'TestServiceType'
$PartitionDescription = "{PartitionScheme = 'Singleton'}"
$InstanceCount = '1'
$url = 'https://www.contoso.com'
$headers = 'our headers'
$bodyTest = @{
ServiceKind = $ServiceKind
ApplicationName = $ApplicationName
ServiceName = $ServiceName
ServiceTypeName = $ServiceTypeName
PartitionDescription = $PartitionDescription
}
Invoke-RestMethod -Uri $url -Headers $headers -body $body -Method Post -ContentType ‘application/json’
错误消息:
Invoke-RestMethod : {"Error":{"Code":"E_INVALIDARG","Message":"The request body can't be deserialized. Make sure it contains a valid PartitionedServiceDescWrapper object."}}
我确定它与$PartitionDescription
值有关,但是我无法获得任何语法才能正常工作。如果我通过API调用而没有使用$body
参数,则不会出错。
答案 0 :(得分:2)
您没有正确嵌套对象:
$body = @{
ServiceKind = 'Custom'
ApplicationName = 'TestApp'
ServiceName = 'TestService'
ServiceTypeName = 'TestServiceType'
PartitionDescription = @{
PartitionScheme = 'Singleton'
}
InstanceCount = '1'
} | ConvertTo-Json
要进一步改善这一点:
$irmParams = @{
Uri = 'https://www.contoso.com'
Method = 'POST'
ContentType = 'application/json'
Headers = @{ Key = 'Value' }
Body = @{
ServiceKind = 'Custom'
ApplicationName = 'TestApp'
ServiceName = 'TestService'
ServiceTypeName = 'TestServiceType'
PartitionDescription = @{
PartitionScheme = 'Singleton'
}
InstanceCount = '1'
} | ConvertTo-Json
}
Invoke-RestMethod @irmParams