【发布时间】:2020-05-03 17:35:26
【问题描述】:
我目前正在开发一个 ASP.NET Core Web API (v3.1)(加上一个 PowerShell 脚本)。
控制器
[Route("api/[controller]")]
[ApiController]
public class RegisterDeviceController : ControllerBase
{
private readonly SCMDB _context;
public RegisterDeviceController(SCMDB context)
{
_context = context;
}
// POST: api/RegisterDevice
[HttpPost]
public async Task<ActionResult<Device>> PostDevice(Device device)
{
if (device.SiteKey == null)
return StatusCode(406,"NoSiteKeyDefined!");
return null;
}
}
“消费者”是一个 PowerShell 脚本:
# Post to web api
try{
$response = Invoke-RestMethod -Uri "$ScmWebApiUrl" -Method Post -Body $JsonString -ContentType "application/json"
}
catch {
$err = $_.Exception
}
Write-Host $ErrResp
我想弄清楚的是:如何获取 ResponseText“NoSiteKeyDefined!”在 PowerShell 中。
我明白了:
[DBG]: PS C:\Windows\system32>> $err.Message
The remote server returned an error: (406) Not Acceptable.
但我还需要消息(在这种情况下 -> NoSiteKeyDefined!)
不一定是 406 错误代码,也可以是另一个“ActionResult”或响应。我也试过它 return BadRequest("NoSiteKeyDefined!") 但我在 $response 和 $err 对象中都没有找到这条消息。重要的是我可以传递可以在 PowerShell 脚本中接收和处理的消息。
【问题讨论】:
-
你的
$JsonString怎么样?在VS中调试的时候能看出来它的价值吗? -
@Avshalom:基本上 $JsonString 是不相关的。唯一相关的是 $response 或者 $_.Exception -> 这是 PowerShell 从 REST API 获取/接收的内容。
标签: powershell rest asp.net-core webapi