通过Azure API管理的C#表达式出现ToString()错误

时间:2019-07-17 10:50:05

标签: azure azure-api-management

在尝试将类型转换为字符串时,出现以下错误:

  <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://docs.microsoft.com/en-us/azure/api-management/api-management-policy-expressions

2 个答案:

答案 0 :(得分:1)

.ToString()将不起作用。

改为使用以下表达式:

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

,或者如果变量不存在或为空,则希望保留默认字符串为空:

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

答案 1 :(得分:0)

您可以尝试如下铸造:

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