【发布时间】:2020-05-03 07:29:11
【问题描述】:
我需要使用 PowerShell 脚本将 Json-body HttpPost 到 ASP.NET Core Web Api 端点(控制器)。
$CurrentWindowsIdentity = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CurrentPrincipalName = $CurrentWindowsIdentity.Identity.Name
# Build JSON payload
$JsonString = @"
{
"CurrentPrincipalName":"$CurrentPrincipalName"
}
"@
$response = Invoke-RestMethod -Uri "https://webapiendpoint.tld/api/somecontroller" -Method Post -Body $JsonString -ContentType "application/json"
由于变量 $CurrentPrincipalName 的值可以是域\用户名,因此 json 获取无效,因为反斜杠没有正确转义。
web api 的日志出错:
JSON input formatter threw an exception: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName | LineNumber: 15 | BytePositionInLine: 36.
System.Text.Json.JsonException: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName
我如何确保在创建 json 字符串和添加变量时——当然无法控制其值——json 字符串得到正确转义?
我也尝试过 ConvertTo-Json 之类的:
$JsonConverted = $JsonString | ConvertTo-Json
然后 HttpPost 那个对象,但那更糟:
JSON input formatter threw an exception: The JSON value could not be converted to solutionname.model. Path: $ | LineNumber: 0 | BytePositionInLine: 758.
【问题讨论】:
-
顺便说一句
$JsonString | ConvertTo-Json:ConvertTo-Json旨在将从哈希表或(自定义)对象转换为 JSON;如果您将已经是 JSON 字符串的内容传递给它,您将得到一个 JSON 字符串值(用文字双引号括起来),并且输入对象结构丢失。试试'{ "foo": 1 }' | ConvertTo-Json
标签: json powershell