You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure API Management出站策略中读取SOAP消息Age字段并存为变量

Extract SOAP Age Field to Variable in Azure API Management Outbound Policy

Hey there! Let's walk through how to pull the Age value from your SOAP request and store it in a variable you can use in your outbound policy. The key here is handling the SOAP namespaces correctly—they're easy to overlook but critical for targeting the right nodes.

Step 1: Extract Age in the Inbound Policy

First, we'll use the set-variable policy in the inbound section to grab the value before moving to the backend. This ensures the variable is available when we get to the outbound stage.

Here's the full policy snippet:

<inbound>
    <base />
    <set-variable name="requestAge" value="@(
        XPathContext context = new XPathContext();
        // Register the namespaces from your SOAP envelope
        context.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
        context.AddNamespace("ns0", "http://TempNameSpace");
        // Target the Age node using the registered namespaces
        var ageNode = XPathSelectSingleNode(context, context.DocumentElement, "/s:Envelope/s:Body/ns0:Root/Age");
        // Handle null case to avoid runtime errors if Age is missing
        return ageNode != null ? ageNode.InnerText : "0";
    )" />
</inbound>

What's happening here?

  • We create an XPathContext to register the namespaces used in your SOAP message. Without this, your XPath query won't find the nodes because XML parsers treat namespaces as part of the node's identity.
  • The XPath expression /s:Envelope/s:Body/ns0:Root/Age directly targets the Age element under your SOAP body and root node.
  • We add a null check to handle cases where the Age field might be missing—this prevents unexpected errors in your policy execution.

Step 2: Use the Variable in the Outbound Policy

Now that the requestAge variable is stored in the APIM context, you can reference it anywhere in the outbound policy. For example, if you want to add it to a response header or modify the outbound payload:

<outbound>
    <!-- Example: Add the Age value to a custom response header -->
    <set-header name="X-Request-Age" value="@((string)context.Variables["requestAge"])" />
    <base />
</outbound>

Quick Notes

  • Make sure the policy is attached to the correct API or operation in your APIM instance.
  • If you need to work with numeric values (like doing calculations with the age), you can parse the string to an integer: int.Parse((string)context.Variables["requestAge"])—just be sure to add error handling if the value might not be a valid number.

内容的提问来源于stack exchange,提问作者Jagan behera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:22:51