適用於:所有 APIM 層
本文討論的原則運算式語法為 C# 7。 每個運算式皆可存取:
語法
-
單一陳述式運算式:
- 以
@(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 |
(建構函式),Add、AddDays、AddHours、AddMilliseconds、AddMinutes、AddMonths、AddSeconds、AddTicks、AddYears、Date、Day、DayOfWeek、DayOfYear、DaysInMonth、Hour、IsDaylightSavingTime、IsLeapYear、MaxValue、Millisecond、Minute、MinValue、Month、Now、Parse、Second、Subtract、Ticks、TimeOfDay、Today、ToString、UtcNow、Year |
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 |
AddressFamily、Equals、、GetAddressBytesIsLoopback、Parse、、、 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 |
除了無參數外 Create() |
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 |
(建構函式),IsMatch、Match、Matches、Replace、Unescape、Split |
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: IApiDeployment經過時間: TimeSpan - Timestamp 值和目前時間的時間間隔GraphQLLastErrorOperationRequestRequestId:Guid - 唯一要求識別碼ResponseSubscriptionTimestamp:DateTime - 收到要求的時間點Tracing:bool - 指出追蹤是開啟或關閉 使用者 Variables: IReadOnlyDictionary<string, object>void Trace(message: string) Workspace |
context.Api |
Id: stringIsCurrentRevision: boolName: stringPath: stringRevision: stringServiceUrl: IUrlVersion: string |
context.Deployment |
GatewayGatewayId:string (針對受控閘道傳回「managed」)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id:string (針對受控閘道傳回「managed」)InstanceId:string (針對受控閘道傳回「managed」)IsManaged: bool |
context.Deployment.SustainabilityInfo |
CurrentCarbonIntensity: 枚舉 碳強度類別 |
context.GraphQL |
GraphQLArguments: IGraphQLDataObjectParent: IGraphQLDataObject範例 |
context.LastError |
Source: stringReason: stringMessage: stringScope: stringSection: stringPath: stringPolicyId: string如需 context.LastError 的詳細資訊,請參閱錯誤處理。 |
context.Operation |
Id: stringMethod: stringName: stringUrlTemplate: string |
context.Product |
ApprovalRequired: boolGroups: IEnumerable<IGroup>Id: stringName: stringState: enum ProductState {NotPublished, Published}SubscriptionsLimit: int?SubscriptionRequired: bool |
context.Request |
Body:如果要求不包含本文,即 IMessageBody 或 null。Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2Headers: IReadOnlyDictionary<string, string[]>IpAddress: stringMatchedParameters: IReadOnlyDictionary<string, string>Method: stringOriginalUrl: IUrlUrl: IUrlPrivateEndpointConnection:如果要求不是來自私人端點連線,即 IPrivateEndpointConnection 或 null。 |
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: string如果找不到標頭,即傳回以逗號分隔的要求標頭值或 defaultValue。 |
context.Response |
Body: IMessageBodyHeaders: IReadOnlyDictionary<string, string[]>StatusCode: intStatusReason: string |
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: string如果找不到標頭,即傳回以逗號分隔的回應標頭值或 defaultValue。 |
context.Subscription |
CreatedDate: DateTimeEndDate: DateTime?Id: stringKey: stringName: stringPrimaryKey: stringSecondaryKey: stringStartDate: DateTime? |
context.User |
Email: stringFirstName: stringGroups: IEnumerable<IGroup>Id: stringIdentities: IEnumerable<IUserIdentity>LastName: stringNote: stringRegistrationDate: DateTime |
context.Workspace |
Id: stringName: string |
IApi |
Id: stringName: stringPath: stringProtocols: IEnumerable<string>ServiceUrl: IUrlSubscriptionKeyParameterNames: ISubscriptionKeyParameterNames |
IGraphQLDataObject |
待定 |
IGroup |
Id: stringName: 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: stringGroupId: stringMemberName: string如需詳細資訊,請參閱 REST API。 |
IUrl |
Host: stringPath: stringPort: intQuery: IReadOnlyDictionary<string, string[]>QueryString: stringScheme: string |
ISubscriptionKeyParameterNames |
Header: stringQuery: string |
string IUrl.Query.GetValueOrDefault(queryParameterName: string, defaultValue: string) |
queryParameterName: stringdefaultValue: string如果找不到參數,即傳回以逗號分隔的查詢參數值或 defaultValue。 |
IUserIdentity |
Id: stringProvider: string |
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) |
variableName: stringdefaultValue: T如果找不到變數,即傳回轉換為 T 或 defaultValue 類型的變數值。如果指定的類型不符合傳回變數的實際類型,此方法會擲回例外狀況。 |
BasicAuthCredentials AsBasic(input: this string) |
input: string如果輸入參數包含有效的 HTTP 基本驗證授權要求標頭值,則方法會傳回類型為 BasicAuthCredentials 的物件;否則方法會傳回 null。 |
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) |
input: stringresult: out BasicAuthCredentials如果輸入參數包含要求標頭中有效的 HTTP 基本驗證授權值,方法會傳回 true,且結果參數包含類型為 BasicAuthCredentials 的值,否則方法會傳回 false。 |
BasicAuthCredentials |
Password: stringUserId: string |
Jwt AsJwt(input: this string) |
input: string如果輸入參數包含有效的 JWT 值,則方法會傳回 型 Jwt別的物件,否則方法會傳 null回 。 |
bool TryParseJwt(input: this string, result: out Jwt) |
input: stringresult: out Jwt如果輸入參數包含有效的 JWT 值,則方法會 true 傳回 ,而結果參數包含 類型的 Jwt值,否則方法會傳 false回 。 |
Jwt |
Algorithm: stringAudiences: IEnumerable<string>Claims: IReadOnlyDictionary<string, string[]>ExpirationTime: DateTime?Id: stringIssuer: stringIssuedAt: DateTime?NotBefore: DateTime?Subject: stringType: string |
string Jwt.Claims.GetValueOrDefault(claimName: string, defaultValue: string) |
claimName: stringdefaultValue: 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。 |
相關內容
如需使用原則的詳細資訊,請參閱:
- 教學課程:轉換及保護 API
- 原則參考,取得原則陳述式及其設定的完整清單
- 政策表達
- 設定或編輯原則
- 重複使用原則設定
- 原則程式碼片段存放庫 (英文)
- 原則遊樂場存放庫
- Azure API 管理 原則工具組
- 取得 Copilot 協助以建立、說明及疑難排解原則
如需詳細資訊,請參閱:
- 了解如何提供內容資訊給您的後端服務。 使用設定查詢字串參數和設定 HTTP 標頭原則來提供此資訊。
- 了解如何使用驗證 JWT 原則來根據權杖宣告預先授與作業的存取權。
- 瞭解如何使用 API 追蹤 來偵測原則的評估方式和這些評估的結果。
- 了解如何使用運算式搭配從快取中取得和儲存至快取原則,來設定 API 管理回應的快取。 設定一段持續時間,使其符合備用服務中
Cache-Control指示詞所指定的後端服務回應快取。 - 了解如何執行內容篩選。 使用控制流程和設定本文原則,移除「從後端收到的回應」中的資料元素。
- 若要下載原則陳述式,請參閱 api-management-samples/policies GitHub 存放庫。