Rediger

Del via


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

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"))" />

For more information about working with policies, see: