How do I access a route parameter in Azure API Management

Viewed 1972

Query string parameter

I have seen plenty of examples of reading query string parameters.

For example take the following URI:

/api/Profile?id={accountId}

The accountId can be read in the policy xml using the following syntax:

context.Request.Url.Query["accountId"]

Route parameter

But what if my URI is structured as:

/api/profiles/{accountId}

How do I read accountId in the policy xml when the parameter is not in the query string?

2 Answers

Using the example above I can read the accountId by the following syntax:

context.Request.MatchedParameters["accountId"]

For example I could assign it to a variable for usage elsewhere in the APIM policy file:

<set-variable name="account-id" value="@(context.Request.MatchedParameters["accountId"])" />

There isn't a massive amount of documentation about it, but thankfully there is at least some mention of the Context variable on docs.microsoft.com.

There is a GitHub repository with quite some snippets including your use case: https://github.com/Azure/api-management-policy-snippets/blob/master/policy-expressions/README.md

For your concrete example, you can use this:

context.Request.MatchedParameters.GetValueOrDefault("accountId", "optional-default-value")

The benefit compared to the other solution is that the policy evaluation does not fail if the URI parameter does not exist. It will use the default value as a fallback instead. Otherwise a 500 Internal Server Error would be returned.

Related