Pingpong
Pingpong

Reputation: 8009

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

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

Upvotes: 5

Views: 3133

Answers (2)

Silly John
Silly John

Reputation: 1704

You can try casting like below:

@((string)context.Variables["a"]))

Upvotes: 0

Kai Walter
Kai Walter

Reputation: 4041

.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",""))

Upvotes: 8

Related Questions