I need to HttpPost a Json-body to a ASP.NET Core Web Api endpoint (controller) using a PowerShell script.
$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"
Since the value of the variable $CurrentPrincipalName can be domain\username, the json get's invalid because of the backslash, which is not properly escaped.
Error in the log of the 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
How can i make sure that when creating a json string and adding variables - whose values of course can not be controlled - the json string gets properly escaped?
i also tried ConvertTo-Json like:
$JsonConverted = $JsonString | ConvertTo-Json
and then HttpPost that object, but that was even worse:
JSON input formatter threw an exception: The JSON value could not be converted to solutionname.model. Path: $ | LineNumber: 0 | BytePositionInLine: 758.