你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于:所有 API 管理层级
本文讨论 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、TryParse、ToString |
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、GetAddressBytes、IsLoopback、Parse、TryParse、ToString |
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、Length、Value |
System.Text.RegularExpressions.CaptureCollection |
Count、Item |
System.Text.RegularExpressions.Group |
Captures、Success |
System.Text.RegularExpressions.GroupCollection |
Count、Item |
System.Text.RegularExpressions.Match |
Empty、Groups、Result |
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: IApiDeploymentElapsed: 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: stringCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id: string(为托管网关返回“managed”)InstanceId: string(为托管网关返回“managed”)IsManaged: bool |
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 Basic Authentication 授权请求标头值,此方法会返回类型为 BasicAuthCredentials 的对象;否则,此方法会返回 null。 |
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) |
input: stringresult: out BasicAuthCredentials如果输入参数包含请求标头中的有效 HTTP Basic Authentication 授权值,此方法会返回 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 存储库。