从 powershell 调用 API 时,Post 方法参数为 null。 下面是 JSON
"TestCase":{
"tc_name":"TestCase1"
},
"3":{
"scn_desc":"Create Client34345",
"test_status":"PASS",
"error_link":""
} ,
"4":{
"scn_desc":"Create Client43634",
"test_status":"PASS",
"error_link":""
},
"5":{
"scn_desc":"Create Client346346",
"test_status":"PASS",
"error_link":""
}
}
$json 包含上面的 json 数组。 电源外壳: 调用WebRequest
-Uri http://localhost:65452/api/e10/e10PostTCData -Method Post -Body $json -ContentType 'application/json'
API:
[Route("e10PostTCData/")]
[HttpPost]
public HttpResponseMessage PostResults([FromBody]JsonArray jsonArray )
{
}
public class JsonArray
{
public string json { get; set; }
}
其他方式:
[Route("e10PostTCData/")]
[HttpPost]
public HttpResponseMessage PostResults([FromBody]String jsonArray )
{
}
这两种方法都显示 null 作为参数。请指教。
最佳答案
在这样的形式中,您的服务期望接收顶层带有 json
字段的 json,与您的类 JsonArray.json
字段相同。因此,在这种情况下,您的请求正文应该类似于:
{
"json": "Whatever text you need to pass here"
}
如果您想传递 JSON 正文,则需要一个类,该类具有与 JSON 的键相同的所有字段。
否则,您可以将 JSON 作为字符串读取,转换为 JSON 并手动处理,例如:
[Route("e10PostTCData")]
[HttpPost]
public async Task<string> PostResults()
{
var bytes = new byte[(int)Request.ContentLength.Value];
await Request.Body.ReadAsync(bytes, 0, bytes.Length);
var content = Encoding.UTF8.GetString(bytes);
var json = JObject.Parse(content);
return json["TestCase"]["tc_name"].ToString();
}
对于 json 正文:
{
"TestCase":{
"tc_name":"TestCase1"
},
"3": {
"scn_desc":"Create Client34345",
"test_status":"PASS",
"error_link":""
} ,
"4":{
"scn_desc":"Create Client43634",
"test_status":"PASS",
"error_link":""
},
"5":{
"scn_desc":"Create Client346346",
"test_status":"PASS",
"error_link":""
}
}
回应
TestCase1
更新: 如果您想接收 JSON 作为端点的字符串参数:
public string PostResults([FromBody]string jsonStr)
{
// Use JObject class methods Parse or ToObject (deserialize) your string into object
return jsonStr;
}
那么您的请求应该是多行字符串,而不是 JSON,这非常不方便,除非您是端点的唯一用户。例如:
'{
"TestCase":{
"tc_name":"TestCase1"
},
"3": {
"scn_desc":"Create Client34345",
"test_status":"PASS",
"error_link":""
} ,
"4":{
"scn_desc":"Create Client43634",
"test_status":"PASS",
"error_link":""
},
"5":{
"scn_desc":"Create Client346346",
"test_status":"PASS",
"error_link":""
}
}'
更新: 我不确定 PowerShell 的所有细节,但以下内容对我有用:
> $obj='{
"TestCase":{
"tc_name":"TestCase1"
}
}'
> Invoke-WebRequest http://localhost:65452/api/e10/e10PostTCData -Body $(echo $obj | ConvertTo-Json) -Method POST -ConventType "application/json"
关于c# - 从 powershell 调用 api 时,空值来自 Post 方法(FromBody),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55692232/