Search code examples
azureurl-rewritingpolicyazure-api-management

Policy rewrite-uri To Append Context Variable in Azure APIM


What is the approach to a simple append to the url of a context variable such as context.Variables["accountKey"] during a policy rewrite?

The end result should be /accounts/232.

I have success earlier in setting it

set-variable (0.003 ms)
{
    "message": "Context variable was successfully set.",
    "name": "accountKey",
    "value": "232"
}

One of the things tried:

<policies>
    <inbound>
        <base />
        <rewrite-uri template="/accounts/{accountKey}" />
    </inbound>

But I get this error

> Error Receive
>     rewrite-uri (0.260 ms) {
>     "messages": [
>         null,
>         "Variable accountKey has no value.",
>         "Variable accountKey has no value."
>     ] }

Solution

  • Configure the inbound rule in the policy as follows:

    <inbound>
        <base />
        <set-variable name="accountKey" value="232" />
        <rewrite-uri template="@{
            return "/account/" + context.Variables.GetValueOrDefault<string>("accountKey");
        }"/>
    </inbound>
    

    {} in rewrite-uri are for query string parameters in the original request URL.

    Find more details about rewrite-uri section in the Microsoft docs at Rewrite URL - API Management transformation policies.