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 All
Newtonsoft.Json.JsonConvert SerializeObjectDeserializeObject
Newtonsoft.Json.Linq.Extensions All
Newtonsoft.Json.Linq.JArray All
Newtonsoft.Json.Linq.JConstructor All
Newtonsoft.Json.Linq.JContainer All
Newtonsoft.Json.Linq.JObject All
Newtonsoft.Json.Linq.JProperty All
Newtonsoft.Json.Linq.JRaw All
Newtonsoft.Json.Linq.JToken All
Newtonsoft.Json.Linq.JTokenType All
Newtonsoft.Json.Linq.JValue All
System.Array All
System.BitConverter All
System.Boolean All
System.Byte All
System.Char All
System.Collections.Generic.Dictionary<TKey, TValue> All
System.Collections.Generic.HashSet<T> All
System.Collections.Generic.ICollection<T> All
System.Collections.Generic.IDictionary<TKey, TValue> All
System.Collections.Generic.IEnumerable<T> All
System.Collections.Generic.IEnumerator<T> All
System.Collections.Generic.IList<T> All
System.Collections.Generic.IReadOnlyCollection<T> All
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> All
System.Collections.Generic.ISet<T> All
System.Collections.Generic.KeyValuePair<TKey, TValue> All
System.Collections.Generic.List<T> All
System.Collections.Generic.Queue<T> All
System.Collections.Generic.Stack<T> All
System.Convert All
System.DateTime (构造函数)、AddAddDaysAddHoursAddMillisecondsAddMinutesAddMonthsAddSecondsAddTicksAddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonth, 、NowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear
System.DateTimeKind Utc
System.DateTimeOffset All
System.Decimal All
System.Double All
System.Enum ParseTryParseToString
System.Exception All
System.Guid All
System.Int16 All
System.Int32 All
System.Int64 All
System.IO.StringReader All
System.IO.StringWriter All
System.Linq.Enumerable All
System.Math All
System.MidpointRounding All
System.Net.IPAddress AddressFamilyEqualsGetAddressBytesIsLoopbackParseTryParseToString
System.Net.WebUtility All
System.Nullable All
System.Random All
System.SByte All
System.Security.Cryptography.AsymmetricAlgorithm All
System.Security.Cryptography.CipherMode All
System.Security.Cryptography.HashAlgorithm All
System.Security.Cryptography.HashAlgorithmName All
System.Security.Cryptography.HMAC All
System.Security.Cryptography.HMACMD5 All
System.Security.Cryptography.HMACSHA1 All
System.Security.Cryptography.HMACSHA256 All
System.Security.Cryptography.HMACSHA384 All
System.Security.Cryptography.HMACSHA512 All
System.Security.Cryptography.KeyedHashAlgorithm All
System.Security.Cryptography.MD5 All
System.Security.Cryptography.Oid All
System.Security.Cryptography.PaddingMode All
System.Security.Cryptography.RNGCryptoServiceProvider All
System.Security.Cryptography.RSA All
System.Security.Cryptography.RSAEncryptionPadding All
System.Security.Cryptography.RSASignaturePadding All
System.Security.Cryptography.SHA1 All
System.Security.Cryptography.SHA1Managed All
System.Security.Cryptography.SHA256 All
System.Security.Cryptography.SHA256Managed All
System.Security.Cryptography.SHA384 All
System.Security.Cryptography.SHA384Managed All
System.Security.Cryptography.SHA512 All
System.Security.Cryptography.SHA512Managed All
System.Security.Cryptography.SymmetricAlgorithm All
System.Security.Cryptography.X509Certificates.PublicKey All
System.Security.Cryptography.X509Certificates.RSACertificateExtensions All
System.Security.Cryptography.X509Certificates.X500DistinguishedName Name
System.Security.Cryptography.X509Certificates.X509Certificate All
System.Security.Cryptography.X509Certificates.X509Certificate2 All
System.Security.Cryptography.X509Certificates.X509ContentType All
System.Security.Cryptography.X509Certificates.X509NameType All
System.Single All
System.String All
System.StringComparer All
System.StringComparison All
System.StringSplitOptions All
System.Text.Encoding All
System.Text.RegularExpressions.Capture IndexLengthValue
System.Text.RegularExpressions.CaptureCollection CountItem
System.Text.RegularExpressions.Group CapturesSuccess
System.Text.RegularExpressions.GroupCollection CountItem
System.Text.RegularExpressions.Match EmptyGroupsResult
System.Text.RegularExpressions.Regex (构造函数)、IsMatchMatchMatchesReplaceUnescapeSplit
System.Text.RegularExpressions.RegexOptions All
System.Text.StringBuilder All
System.TimeSpan All
System.TimeZone All
System.TimeZoneInfo.AdjustmentRule All
System.TimeZoneInfo.TransitionTime All
System.TimeZoneInfo All
System.Tuple All
System.UInt16 All
System.UInt32 All
System.UInt64 All
System.Uri All
System.UriPartial All
System.Xml.Linq.Extensions All
System.Xml.Linq.XAttribute All
System.Xml.Linq.XCData All
System.Xml.Linq.XComment All
System.Xml.Linq.XContainer All
System.Xml.Linq.XDeclaration All
System.Xml.Linq.XDocument 全部(Load 除外)
System.Xml.Linq.XDocumentType All
System.Xml.Linq.XElement All
System.Xml.Linq.XName All
System.Xml.Linq.XNamespace All
System.Xml.Linq.XNode All
System.Xml.Linq.XNodeDocumentOrderComparer All
System.Xml.Linq.XNodeEqualityComparer All
System.Xml.Linq.XObject All
System.Xml.Linq.XProcessingInstruction All
System.Xml.Linq.XText All
System.Xml.XmlNodeType All

上下文变量

在每个策略context中均可隐式使用 变量。 其成员:

  • 提供与 API 请求响应相关的信息,以及相关的属性。
  • 都是只读的。
上下文变量 允许的方法、属性和参数值
context Api: IApi

Deployment

Elapsed: TimeSpan - Timestamp 的值与当前时间之间的时间间隔

GraphQL

LastError

Operation

Request

RequestId: Guid - 唯一请求标识符

Response

Subscription

Timestamp: DateTime - 收到请求的时间点

Tracing: bool - 指示是打开还是关闭跟踪

用户

Variables: IReadOnlyDictionary<string, object>

void Trace(message: string)

Workspace
context.Api Id: string

IsCurrentRevision: bool

Name: string

Path: string

Revision: string

ServiceUrl: IUrl

Version: string
context.Deployment Gateway

GatewayId: string(为托管网关返回“managed”)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string(为托管网关返回“managed”)

InstanceId: string(为托管网关返回“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
context.Request BodyIMessageBodynull(如果请求没有正文)。

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnectionIPrivateEndpointConnectionnull(如果请求不是来自专用终结点连接)。
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
context.Workspace Id: string

Name: string
IApi Id: string

Name: string

Path: string

Protocols: IEnumerable<string>

ServiceUrl: IUrl

SubscriptionKeyParameterNames: ISubscriptionKeyParameterNames
IGraphQLDataObject TBD

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
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) variableName: string

defaultValue: T

如果找不到变量,则会返回强制转换为 TdefaultValue 类型的变量值。

如果指定的类型与已返回变量的实际类型不符,此方法会引发异常。
BasicAuthCredentials AsBasic(input: this string) input: string

如果输入参数包含有效的 HTTP Basic Authentication 授权请求标头值,此方法会返回类型为 BasicAuthCredentials 的对象;否则,此方法会返回 null。
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

如果输入参数包含请求标头中的有效 HTTP Basic Authentication 授权值,此方法会返回 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

有关使用策略的详细信息,请参阅:

更多相关信息: