ToString() error with C# expression via Azure API Management
Asked Answered
O

2

5

I got errors below trying to converting a type to string, like below:

  <set-variable name="a" value="@(context.Variables["a"].ToString())" />
Error in element 'set-variable' on line 16, column 10: Usage of member 'ToString' of type 'System.Object' is not supported within expressions


 <set-variable name="a" value="@(context.Variables["a"])" />
    Error in element 'set-variable' on line 16, column 10: Expression return type 'System.Object' is not allowed

https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions

Outstay answered 17/7, 2019 at 10:50 Comment(0)
C
8

.ToString() will not work.

Use this expression instead:

@(context.Variables.GetValueOrDefault<string>("a"))

or if you want to have and empty default string in case the variable is not existing or null:

@(context.Variables.GetValueOrDefault<string>("a",""))
Cracknel answered 17/7, 2019 at 13:33 Comment(0)
H
0

You can try casting like below:

@((string)context.Variables["a"]))
Hel answered 18/7, 2019 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.