API 管理原則運算式

適用於:所有 API 管理 層

本文討論的原則運算式語法為 C# 7。 每個運算式皆可存取:

  • 隱含提供的 context 變數。
  • 允許的 .NET Framework 類型子集

語法

  • 單一陳述式運算式:
    • @(expression) 括住,其中 expression 為格式正確的 C# 運算式陳述式。
  • 多重陳述式運算式:
    • @{expression} 括住。
    • 多重陳述式運算式內的所有程式碼路徑都必須以 return 陳述式結尾。

範例

@(true)

@((1+1).ToString())

@("Hi There".Length)

@(Regex.Match(context.Response.Headers.GetValueOrDefault("Cache-Control",""), @"max-age=(?<maxAge>\d+)").Groups["maxAge"]?.Value)

@(context.Variables.ContainsKey("maxAge") ? int.Parse((string)context.Variables["maxAge"]) : 3600)

@{
  string[] value;
  if (context.Request.Headers.TryGetValue("Authorization", out value))
  {
      if(value != null && value.Length > 0)
      {
          return Encoding.UTF8.GetString(Convert.FromBase64String(value[0]));
      }
  }
  return null;

}

使用方式

除非另行指定原則參考,否則 API 管理原則可使用運算式作為屬性值或文字值。

重要

定義原則時,原則運算式只能進行有限的驗證。 在執行階段,運算式由閘道執行。 原則運算式所產生的任何例外狀況皆會導致執行階段發生錯誤。

原則運算式中允許的 .NET Framework 類型

下表列出原則運算式中允許的 .NET Framework 類型和其成員。

類型 支援的成員
Newtonsoft.Json.Formatting 全部
Newtonsoft.Json.JsonConvert SerializeObject, DeserializeObject
Newtonsoft.Json.Linq.Extensions 全部
Newtonsoft.Json.Linq.JArray 全部
Newtonsoft.Json.Linq.JConstructor 全部
Newtonsoft.Json.Linq.JContainer 全部
Newtonsoft.Json.Linq.JObject 全部
Newtonsoft.Json.Linq.JProperty 全部
Newtonsoft.Json.Linq.JRaw 全部
Newtonsoft.Json.Linq.JToken 全部
Newtonsoft.Json.Linq.JTokenType 全部
Newtonsoft.Json.Linq.JValue 全部
System.Array 全部
System.BitConverter 全部
System.Boolean 全部
System.Byte 全部
System.Char 全部
System.Collections.Generic.Dictionary<TKey, TValue> 全部
System.Collections.Generic.HashSet<T> 全部
System.Collections.Generic.ICollection<T> 全部
System.Collections.Generic.IDictionary<TKey, TValue> 全部
System.Collections.Generic.IEnumerable<T> 全部
System.Collections.Generic.IEnumerator<T> 全部
System.Collections.Generic.IList<T> 全部
System.Collections.Generic.IReadOnlyCollection<T> 全部
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> 全部
System.Collections.Generic.ISet<T> 全部
System.Collections.Generic.KeyValuePair<TKey, TValue> 全部
System.Collections.Generic.List<T> 全部
System.Collections.Generic.Queue<T> 全部
System.Collections.Generic.Stack<T> 全部
System.Convert 全部
System.DateTime (建構函式),AddAddDaysAddHoursAddMillisecondsAddMinutesAddMonthsAddSecondsAddTicksAddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonthNowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear
System.DateTimeKind Utc
System.DateTimeOffset 全部
System.Decimal 全部
System.Double 全部
System.Enum Parse、 、 TryParseToString
System.Exception 全部
System.Guid 全部
System.Int16 全部
System.Int32 全部
System.Int64 全部
System.IO.StringReader 全部
System.IO.StringWriter 全部
System.Linq.Enumerable 全部
System.Math 全部
System.MidpointRounding 全部
System.Net.IPAddress AddressFamilyEquals、、IsLoopbackGetAddressBytesParse、、、 TryParseToString
System.Net.WebUtility 全部
System.Nullable 全部
System.Random 全部
System.SByte 全部
System.Security.Cryptography.AsymmetricAlgorithm 全部
System.Security.Cryptography.CipherMode 全部
System.Security.Cryptography.HashAlgorithm 全部
System.Security.Cryptography.HashAlgorithmName 全部
System.Security.Cryptography.HMAC 全部
System.Security.Cryptography.HMACMD5 全部
System.Security.Cryptography.HMACSHA1 全部
System.Security.Cryptography.HMACSHA256 全部
System.Security.Cryptography.HMACSHA384 全部
System.Security.Cryptography.HMACSHA512 全部
System.Security.Cryptography.KeyedHashAlgorithm 全部
System.Security.Cryptography.MD5 全部
System.Security.Cryptography.Oid 全部
System.Security.Cryptography.PaddingMode 全部
System.Security.Cryptography.RNGCryptoServiceProvider 全部
System.Security.Cryptography.RSA 全部
System.Security.Cryptography.RSAEncryptionPadding 全部
System.Security.Cryptography.RSASignaturePadding 全部
System.Security.Cryptography.SHA1 全部
System.Security.Cryptography.SHA1Managed 全部
System.Security.Cryptography.SHA256 全部
System.Security.Cryptography.SHA256Managed 全部
System.Security.Cryptography.SHA384 全部
System.Security.Cryptography.SHA384Managed 全部
System.Security.Cryptography.SHA512 全部
System.Security.Cryptography.SHA512Managed 全部
System.Security.Cryptography.SymmetricAlgorithm 全部
System.Security.Cryptography.X509Certificates.PublicKey 全部
System.Security.Cryptography.X509Certificates.RSACertificateExtensions 全部
System.Security.Cryptography.X509Certificates.X500DistinguishedName Name
System.Security.Cryptography.X509Certificates.X509Certificate 全部
System.Security.Cryptography.X509Certificates.X509Certificate2 全部
System.Security.Cryptography.X509Certificates.X509ContentType 全部
System.Security.Cryptography.X509Certificates.X509NameType 全部
System.Single 全部
System.String 全部
System.StringComparer 全部
System.StringComparison 全部
System.StringSplitOptions 全部
System.Text.Encoding 全部
System.Text.RegularExpressions.Capture Index、 、 LengthValue
System.Text.RegularExpressions.CaptureCollection Count, Item
System.Text.RegularExpressions.Group Captures, Success
System.Text.RegularExpressions.GroupCollection Count, Item
System.Text.RegularExpressions.Match Empty、 、 GroupsResult
System.Text.RegularExpressions.Regex (建構函式),IsMatchMatchMatchesReplaceUnescapeSplit
System.Text.RegularExpressions.RegexOptions 全部
System.Text.StringBuilder 全部
System.TimeSpan 全部
System.TimeZone 全部
System.TimeZoneInfo.AdjustmentRule 全部
System.TimeZoneInfo.TransitionTime 全部
System.TimeZoneInfo 全部
System.Tuple 全部
System.UInt16 全部
System.UInt32 全部
System.UInt64 全部
System.Uri 全部
System.UriPartial 全部
System.Xml.Linq.Extensions 全部
System.Xml.Linq.XAttribute 全部
System.Xml.Linq.XCData 全部
System.Xml.Linq.XComment 全部
System.Xml.Linq.XContainer 全部
System.Xml.Linq.XDeclaration 全部
System.Xml.Linq.XDocument 全部,但 Load 除外
System.Xml.Linq.XDocumentType 全部
System.Xml.Linq.XElement 全部
System.Xml.Linq.XName 全部
System.Xml.Linq.XNamespace 全部
System.Xml.Linq.XNode 全部
System.Xml.Linq.XNodeDocumentOrderComparer 全部
System.Xml.Linq.XNodeEqualityComparer 全部
System.Xml.Linq.XObject 全部
System.Xml.Linq.XProcessingInstruction 全部
System.Xml.Linq.XText 全部
System.Xml.XmlNodeType 全部

內容變數

所有原則運算式皆可隱含使用 context 變數。 其成員會:

  • 提供 API 要求回應的相關資訊,以及相關屬性。
  • 皆為唯讀。
內容變數 允許的方法、屬性和參數值
context Api: IApi

Deployment

經過時間:TimeSpan - Timestamp 值和目前時間的時間間隔

GraphQL

LastError

Operation

Request

RequestIdGuid - 唯一要求識別碼

Response

Subscription

TimestampDateTime - 收到要求的時間點

Tracingbool - 指出追蹤是開啟或關閉

使用者

Variables: IReadOnlyDictionary<string, object>

void Trace(message: string)
context.Api Id: string

IsCurrentRevision: bool

Name: string

Path: string

Revision: string

ServiceUrl: IUrl

Version: string

Workspace: IWorkspace
context.Deployment Gateway

GatewayIdstring (針對受控閘道傳回「managed」)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Idstring (針對受控閘道傳回「managed」)

InstanceIdstring (針對受控閘道傳回「managed」)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

範例
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

如需 context.LastError 的詳細資訊,請參閱錯誤處理
context.Operation Id: string

Method: string

Name: string

UrlTemplate: string
context.Product ApprovalRequired: bool

Groups: IEnumerable<IGroup>

Id: string

Name: string

State: enum ProductState {NotPublished, Published}

SubscriptionsLimit: int?

SubscriptionRequired: bool

Workspace: IWorkspace
context.Request Body:如果要求不包含本文,即 IMessageBodynull

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection:如果要求不是來自私人端點連線,即 IPrivateEndpointConnectionnull
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

如果找不到標頭,即傳回以逗號分隔的要求標頭值或 defaultValue
context.Response Body: IMessageBody

Headers: IReadOnlyDictionary<string, string[]>

StatusCode: int

StatusReason: string
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

如果找不到標頭,即傳回以逗號分隔的回應標頭值或 defaultValue
context.Subscription CreatedDate: DateTime

EndDate: DateTime?

Id: string

Key: string

Name: string

PrimaryKey: string

SecondaryKey: string

StartDate: DateTime?
context.User Email: string

FirstName: string

Groups: IEnumerable<IGroup>

Id: string

Identities: IEnumerable<IUserIdentity>

LastName: string

Note: string

RegistrationDate: DateTime
IApi Id: string

Name: string

Path: string

Protocols: IEnumerable<string>

ServiceUrl: IUrl

SubscriptionKeyParameterNames: ISubscriptionKeyParameterNames
IGraphQLDataObject 待定

IGroup Id: string

Name: string
IMessageBody As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument

- context.Request.Body.As<T>context.Response.Body.As<T> 方法會讀取指定類型 T 的要求和回應訊息本文。

- 或 -

AsFormUrlEncodedContent(bool preserveContent = false)

- context.Request.Body.AsFormUrlEncodedContent()context.Response.Body.AsFormUrlEncodedContent() 方法會讀取要求或回應訊息本文中 URL 編碼的表單資料,並傳回 IDictionary<string, IList<string> 物件。 已解碼的物件支援 IDictionary 作業和下列運算式:ToQueryString()JsonConvert.SerializeObject()ToFormUrlEncodedContent().

根據預設,As<T>AsFormUrlEncodedContent() 方法:
  • 使用原始訊息本文資料流。
  • 傳回後會轉譯為無法使用。

若要避免發生此情況,並讓方法可在本文資料流複本上運作,請將 preserveContent 參數設為 true,如 set-body 原則範例中所示。
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

如需詳細資訊,請參閱 REST API
IUrl Host: string

Path: string

Port: int

Query: IReadOnlyDictionary<string, string[]>

QueryString: string

Scheme: string
ISubscriptionKeyParameterNames Header: string

Query: string
string IUrl.Query.GetValueOrDefault(queryParameterName: string, defaultValue: string) queryParameterName: string

defaultValue: string

如果找不到參數,即傳回以逗號分隔的查詢參數值或 defaultValue
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

Name: string
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) variableName: string

defaultValue: T

如果找不到變數,即傳回轉換為 TdefaultValue 類型的變數值。

如果指定的類型不符合傳回變數的實際類型,此方法會擲回例外狀況。
BasicAuthCredentials AsBasic(input: this string) input: string

如果輸入參數包含有效的 HTTP 基本驗證授權要求標頭值,則方法會傳回類型為 BasicAuthCredentials 的物件;否則方法會傳回 null。
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

如果輸入參數包含要求標頭中有效的 HTTP 基本驗證授權值,方法會傳回 true,且結果參數包含類型為 BasicAuthCredentials 的值,否則方法會傳回 false
BasicAuthCredentials Password: string

UserId: string
Jwt AsJwt(input: this string) input: string

如果輸入參數包含有效的 JWT 權杖值,則方法會傳回類型為 Jwt 的物件;否則方法會傳回 null
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

如果輸入參數包含有效的 JWT 權杖值,則方法會傳回 true,且結果參數包含類型為 Jwt 的值;否則方法會傳回 false
Jwt Algorithm: string

Audiences: IEnumerable<string>

Claims: IReadOnlyDictionary<string, string[]>

ExpirationTime: DateTime?

Id: string

Issuer: string

IssuedAt: DateTime?

NotBefore: DateTime?

Subject: string

Type: string
string Jwt.Claims.GetValueOrDefault(claimName: string, defaultValue: string) claimName: string

defaultValue: string

如果找不到標頭,即傳回以逗號分隔的宣告值或 defaultValue
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - 純要加密的文字

alg - 對稱式加密演算法的名稱

key - 加密金鑰

iv - 初始化媒介

傳回加密的純文字。
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - 純要加密的文字

alg - 加密演算法

傳回加密的純文字。
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - 純要加密的文字

alg - 加密演算法

key - 加密金鑰

iv - 初始化媒介

傳回加密的純文字。
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - 要解密的加密文字

alg - 對稱式加密演算法的名稱

key - 加密金鑰

iv - 初始化媒介

傳回純文字。
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - 要解密的加密文字

alg - 加密演算法

傳回純文字。
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - 要解密的加密文字

alg - 加密演算法

key - 加密金鑰

iv - 初始化媒介

傳回純文字。
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) 執行 X.509 鏈結驗證,而不檢查憑證撤銷狀態。

input - 憑證物件

若驗證成功,則為 true;若驗證失敗則為 false

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

如需詳細資訊,請參閱:

  • 了解如何提供內容資訊給您的後端服務。 使用設定查詢字串參數設定 HTTP 標頭原則來提供此資訊。
  • 了解如何使用驗證 JWT 原則來根據權杖宣告預先授與作業的存取權。
  • 了解如何使用 API 檢查器追蹤,以偵測原則的評估方式及評估結果。
  • 了解如何使用運算式搭配從快取中取得儲存至快取原則,來設定 API 管理回應的快取。 設定一段持續時間,使其符合備用服務中 Cache-Control 指示詞所指定的後端服務回應快取。
  • 了解如何執行內容篩選。 使用控制流程設定本文原則,移除「從後端收到的回應」中的資料元素。
  • 若要下載原則陳述式,請參閱 api-management-samples/policies GitHub 存放庫。