【问题标题】:ASP.NET Core Web Api and PowerShell Invoke-RestMethod (Method Post) plus ResponseText / ReturnValue / ErrorMessageASP.NET Core Web Api 和 PowerShell Invoke-RestMethod (Method Post) 加上 ResponseText / ReturnValue / ErrorMessage
【发布时间】: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


【解决方案1】:

我想弄清楚的是:如何获得 ResponseText“NoSiteKeyDefined!”在 PowerShell 中

如果使用包含 WebException 详细消息的 $_.ExceptionException 属性访问,我可以重现相同的问题。

要获取我们设置的值'NoSiteKeyDefined!',我们可以直接使用Write-Host $_访问它,如下所示。

try{
    $ScmWebApiUrl = 'https://xxxx/api/RegisterDevice'

    $Body = @{
         SiteKey = $NULL
    }

    $JsonString = $Body | ConvertTo-Json

    $response = Invoke-RestMethod -Uri "$ScmWebApiUrl"  -Method Post -Body $JsonString -ContentType 'application/json'
}
catch{
    Write-Host $_
    Write-Host $_.Exception
}

测试结果

【讨论】:

  • 有趣的发现。我无法重现它。您使用的是什么 PowerShell 版本?您可以发布有关您的 $PSVersionTable 的详细信息吗?我的 PSVersion 是:5.1.18362.752。我没有使用 PS .net 核心,因为该脚本需要在 W10 本机安装上运行。
猜你喜欢
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多