你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

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 全部
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 All
System.DateTime (构造函数)、AddAddDaysAddHoursAddMillisecondsAddMinutesAddMonthsAddSecondsAddTicksAddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonth, 、NowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear
System.DateTimeKind Utc
System.DateTimeOffset All
System.Decimal 全部
System.Double All
System.Enum ParseTryParseToString
System.Exception All
System.Guid 全部
System.Int16 全部
System.Int32 全部
System.Int64 全部
System.IO.StringReader 全部
System.IO.StringWriter 全部
System.Linq.Enumerable 全部
System.Math 全部
System.MidpointRounding All
System.Net.IPAddress AddressFamilyEqualsGetAddressBytesIsLoopbackParseTryParseToString
System.Net.WebUtility All
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 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 全部
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 All
System.Xml.Linq.XDocument 全部(Load 除外)
System.Xml.Linq.XDocumentType All
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

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

GraphQL

LastError

Operation

Request

RequestId: Guid - 唯一请求标识符

Response

Subscription

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

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

用户

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

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

Workspace: IWorkspace
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
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
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 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

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

有关详细信息,请参阅: