Azure APIM中动态NamedValue无法替换实际值的解决咨询
解决Azure APIM动态引用NamedValue未替换实际值的问题
你当前的问题是:通过Logic Apps传递NamedValue名称到APIM,期望根据合作方动态加载对应的Salesforce凭据,但策略运行后,生成的token body里NamedValue的占位符(比如{{Project1-Salesforce-Username}})没有被替换成实际存储的值。
问题原因
APIM对{{NamedValue名称}}格式的替换是在策略解析阶段完成的,而你是在运行时通过字符串拼接生成了{{变量名}}格式的内容,这时候已经错过了替换时机,所以APIM不会再解析这些动态生成的占位符。
解决方案
改用APIM运行时APIcontext.NamedValues.GetValueOrDefault()直接获取NamedValue的实际值,替代字符串拼接占位符的方式。修改后的策略如下:
<!-- START Dynamic SF user identification --> <set-variable name="nv_username" value="@(context.Request.Headers.GetValueOrDefault("nv_username"))" /> <set-variable name="nv_password" value="@(context.Request.Headers.GetValueOrDefault("nv_password"))" /> <choose> <when condition="@(context.Request.Headers.ContainsKey("nv_username"))"> <set-variable name="get_tokenbody" value="@($"grant_type=password&client_id={context.NamedValues.GetValueOrDefault("Common-Salesforce-ClientID")}&client_secret={context.NamedValues.GetValueOrDefault("Common-Salesforce-ClientSecret")}&username={context.NamedValues.GetValueOrDefault((string)context.Variables["nv_username"])}&password={context.NamedValues.GetValueOrDefault((string)context.Variables["nv_password"])})" /> </when> <otherwise> <set-variable name="get_tokenbody" value="@($"grant_type=password&client_id={context.NamedValues.GetValueOrDefault("Common-Salesforce-ClientID")}&client_secret={context.NamedValues.GetValueOrDefault("Common-Salesforce-ClientSecret")}&username={context.NamedValues.GetValueOrDefault("Common-Salesforce-Username")}&password={context.NamedValues.GetValueOrDefault("Common-Salesforce-Password")})" /> </otherwise> </choose> <!-- END Dynamic SF user identification -->
说明
context.NamedValues.GetValueOrDefault("NamedValue名称")可以在运行时直接获取对应NamedValue的实际值,不管是静态配置的名称还是动态传入的名称(比如context.Variables["nv_username"]存储的名称)。- 使用C#字符串插值(
$"")让代码更简洁易读,避免复杂的字符串拼接。
修改后重新测试,APIM Trace里的get_tokenbody值会显示实际的凭据内容(敏感信息会被自动脱敏),而不是占位符格式。
内容的提问来源于stack exchange,提问作者amitz27
相关产品推荐
相关产品推荐

