我试图模仿在 powershell 中的 webapi 调用主体中采用的 C# 类定义,以便我可以使用表示为 json 的该对象调用 Rest 方法。我试图实现的 json 结构的一个示例是:
'{
"Name" : "Test" ,
"Items" : [{"Key" : "Test", "Value" : "t2"},{"Key" : "Test2", "Value" : "t3"}]
}'
当设置为 postman 中其余调用的主体时,此 json 有效,如果我用它调用 powershell invokerest-method,则所有字段在 webapi 端都为 null。
这是我当前在 powershell 中的尝试,请注意,Items 实际上是键值对对象的列表。使用下面的代码我只得到 items 中的 1 个项目,其名称和值均为空。
$spec = @{
Name = 'Test'
Items = ,{Name = 'Test', Value = 't2'}, {Name = 'Test2', Value = 't3'}
}
invoke-restmethod $someurl -Method:POST -body $spec | Write-Host
我相当确定我遗漏了 powershell 对象上项目的数组声明中的一些重要内容。
这是剩下的方法:
[HttpPost]
[Route("addorupdateitem")]
public void Add([FromBody] ItemConfigurationDto itemconfig)
{
var serializeObject = Newtonsoft.Json.JsonConvert.SerializeObject(context);
Debug.WriteLine(serializeObject);
}
和对象
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; }
}
最佳答案
已解决问题。我必须设置 -ContentType 'application/json' 并将对象转换为 json,然后再将其添加到正文中。
关于json - 使用具有对象数组属性的 json 对象从 powershell 调用rest方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33526321/