設定變數

適用於:所有 API 管理 層

set-variable 原則會宣告內容變數,並對其指派透過運算式或字串常值指定的值。 如果表示式包含常值,則會轉換成字串,而值的型別將會是 System.String

注意

請依照原則陳述式中提供的順序,來設定原則的元素和子元素。 深入了解如何設定或編輯 APIM 原則

原則陳述式

<set-variable name="variable name" value="Expression | String literal" />

屬性

屬性 描述 必要
NAME 變數的名稱。 不允許使用原則運算式。 Yes
value 變數的值。 此值可為運算式或常值。 允許使用原則運算式。 Yes

使用方式

允許的類型

set-variable 原則中使用的運算式必須傳回下列其中一個基本類型。

  • 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?

範例

下列範例會示範 inbound 區段中的 set-variable 原則。 此設定變數原則會在 User-Agent 要求標頭包含文字 iPadiPhone 時,建立設為 true 的 isMobile 布林內容變數。

<set-variable name="IsMobile" value="@(context.Request.Headers.GetValueOrDefault("User-Agent","").Contains("iPad") || context.Request.Headers.GetValueOrDefault("User-Agent","").Contains("iPhone"))" />

如需使用原則的詳細資訊,請參閱: