Set variable
APPLIES TO: All API Management tiers
The set-variable
policy declares a context variable and assigns it a value specified via an expression or a string literal. If the expression contains a literal it will be converted to a string and the type of the value will be System.String
.
Note
Set the policy's elements and child elements in the order provided in the policy statement. Learn more about how to set or edit API Management policies.
Policy statement
<set-variable name="variable name" value="Expression | String literal" />
Attributes
Attribute | Description | Required |
---|---|---|
name | The name of the variable. Policy expressions aren't allowed. | Yes |
value | The value of the variable. This can be an expression or a literal value. Policy expressions are allowed. | Yes |
Usage
- Policy sections: inbound, outbound, backend, on-error
- Policy scopes: global, workspace, product, API, operation
- Gateways: classic, v2, consumption, self-hosted, workspace
Allowed types
Expressions used in the set-variable
policy must return one of the following basic types.
- System.Boolean
- System.SByte
- System.Byte
- System.UInt16
- System.UInt32
- System.UInt64
- System.Int16
- System.Int32
- System.Int64
- System.Decimal
- System.Single
- System.Double
- System.Guid
- System.String
- System.Char
- System.DateTime
- System.TimeSpan
- System.Byte?
- System.UInt16?
- System.UInt32?
- System.UInt64?
- System.Int16?
- System.Int32?
- System.Int64?
- System.Decimal?
- System.Single?
- System.Double?
- System.Guid?
- System.String?
- System.Char?
- System.DateTime?
Example
The following example demonstrates a set-variable
policy in the inbound section. This set variable policy creates an isMobile
Boolean context variable that is set to true if the User-Agent
request header contains the text iPad
or iPhone
.
<set-variable name="IsMobile" value="@(context.Request.Headers.GetValueOrDefault("User-Agent","").Contains("iPad") || context.Request.Headers.GetValueOrDefault("User-Agent","").Contains("iPhone"))" />
Related policies
Related content
For more information about working with policies, see:
- Tutorial: Transform and protect your API
- Policy reference for a full list of policy statements and their settings
- Policy expressions
- Set or edit policies
- Reuse policy configurations
- Policy snippets repo
- Author policies using Microsoft Copilot in Azure