API 管理策略表达式API Management policy expressions

本文讨论策略表达式语法 C# 7。This article discusses policy expressions syntax is C# 7. 每个表达式都可以访问隐式提供的上下文变量以及允许的 .NET Framework 类型子集Each expression has access to the implicitly provided context variable and an allowed subset of .NET Framework types.

更多相关信息:For more information:

  • 了解如何向后端服务提供上下文信息。See how to supply context information to your backend service. 使用设置查询字符串参数设置 HTTP 标头策略来提供此信息。Use the Set query string parameter and Set HTTP header policies to supply this information.
  • 了解如何使用验证 JWT 策略根据令牌声明预先授予操作访问权限。See how to use the Validate JWT policy to pre-authorize access to operations based on token claims.
  • 了解如何使用 API 检查器跟踪查看策略求值方法和这些求值的结果。See how to use an API Inspector trace to see how policies are evaluated and the results of those evaluations.
  • 了解如何对从缓存获取存储到缓存策略使用表达式,以便配置 API 管理响应缓存。See how to use expressions with the Get from cache and Store to cache policies to configure API Management response caching. 设置持续时间,使之匹配由后端服务的 Cache-Control 指令指定的后端服务响应缓存。Set a duration that matches the response caching of the backend service as specified by the backed service's Cache-Control directive.
  • 了解如何进行内容筛选。See how to perform content filtering. 删除使用控制流设置正文策略从后端接收的响应中的数据元素。Remove data elements from the response received from the backend using the Control flow and Set body policies.
  • 要下载策略语句,请参阅 api-management-samples/policies GitHub 存储库。To download the policy statements, see the api-management-samples/policies GitHub repo.

语法Syntax

单一语句表达式括在 @(expression) 中,其中 expression 是格式正确的 C# 表达式语句。Single statement expressions are enclosed in @(expression), where expression is a well-formed C# expression statement.

多语句表达式括在 @{expression} 中。Multi-statement expressions are enclosed in @{expression}. 多语句表达式中的所有代码路径必须以 return 语句结尾。All code paths within multi-statement expressions must end with a return statement.

示例Examples

@(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;

}

用法Usage

在任何 API 管理策略中,表达式都可用作属性值或文本值(除非策略引用另行指定)。Expressions can be used as attribute values or text values in any API Management policies (unless the policy reference specifies otherwise).

Important

使用策略表达式定义策略时,只能对策略表达式进行有限的验证。When you use policy expressions, there is only limited verification of the policy expressions when the policy is defined. 在运行时,表达式由网关执行,策略表达式生成的任何异常将导致运行时错误。Expressions are executed by the gateway at run-time, any exceptions generated by policy expressions result in a runtime error.

策略表达式中允许的 .NET Framework 类型.NET Framework types allowed in policy expressions

下表列出了策略表达式中允许的 .NET Framework 类型及其成员。The following table lists the .NET Framework types and their members that are allowed in policy expressions.

类型Type 受支持的成员Supported members
Newtonsoft.Json.FormattingNewtonsoft.Json.Formatting 全部All
Newtonsoft.Json.JsonConvertNewtonsoft.Json.JsonConvert SerializeObject、DeserializeObjectSerializeObject, DeserializeObject
Newtonsoft.Json.Linq.ExtensionsNewtonsoft.Json.Linq.Extensions 全部All
Newtonsoft.Json.Linq.JArrayNewtonsoft.Json.Linq.JArray 全部All
Newtonsoft.Json.Linq.JConstructorNewtonsoft.Json.Linq.JConstructor 全部All
Newtonsoft.Json.Linq.JContainerNewtonsoft.Json.Linq.JContainer 全部All
Newtonsoft.Json.Linq.JObjectNewtonsoft.Json.Linq.JObject 全部All
Newtonsoft.Json.Linq.JPropertyNewtonsoft.Json.Linq.JProperty 全部All
Newtonsoft.Json.Linq.JRawNewtonsoft.Json.Linq.JRaw 全部All
Newtonsoft.Json.Linq.JTokenNewtonsoft.Json.Linq.JToken 全部All
Newtonsoft.Json.Linq.JTokenTypeNewtonsoft.Json.Linq.JTokenType 全部All
Newtonsoft.Json.Linq.JValueNewtonsoft.Json.Linq.JValue 全部All
System.ArraySystem.Array 全部All
System.BitConverterSystem.BitConverter 全部All
System.BooleanSystem.Boolean 全部All
System.ByteSystem.Byte 全部All
System.CharSystem.Char 全部All
System.Collections.Generic.Dictionary<TKey, TValue>System.Collections.Generic.Dictionary<TKey, TValue> 全部All
System.Collections.Generic.HashSet<T>System.Collections.Generic.HashSet<T> 全部All
System.Collections.Generic.ICollection<T>System.Collections.Generic.ICollection<T> 全部All
System.Collections.Generic.IDictionary<TKey, TValue>System.Collections.Generic.IDictionary<TKey, TValue> 全部All
System.Collections.Generic.IEnumerable<T>System.Collections.Generic.IEnumerable<T> 全部All
System.Collections.Generic.IEnumerator<T>System.Collections.Generic.IEnumerator<T> 全部All
System.Collections.Generic.IList<T>System.Collections.Generic.IList<T> 全部All
System.Collections.Generic.IReadOnlyCollection<T>System.Collections.Generic.IReadOnlyCollection<T> 全部All
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> 全部All
System.Collections.Generic.ISet<T>System.Collections.Generic.ISet<T> 全部All
System.Collections.Generic.KeyValuePair<TKey, TValue>System.Collections.Generic.KeyValuePair<TKey, TValue> 全部All
System.Collections.Generic.List<T>System.Collections.Generic.List<T> 全部All
System.Collections.Generic.Queue<T>System.Collections.Generic.Queue<T> 全部All
System.Collections.Generic.Stack<T>System.Collections.Generic.Stack<T> 全部All
System.ConvertSystem.Convert 全部All
System.DateTimeSystem.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(Constructor), 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.DateTimeKindSystem.DateTimeKind UtcUtc
System.DateTimeOffsetSystem.DateTimeOffset 全部All
System.DecimalSystem.Decimal 全部All
System.DoubleSystem.Double 全部All
System.ExceptionSystem.Exception 全部All
System.GuidSystem.Guid 全部All
System.Int16System.Int16 全部All
System.Int32System.Int32 全部All
System.Int64System.Int64 全部All
System.IO.StringReaderSystem.IO.StringReader 全部All
System.IO.StringWriterSystem.IO.StringWriter 全部All
System.Linq.EnumerableSystem.Linq.Enumerable 全部All
System.MathSystem.Math 全部All
System.MidpointRoundingSystem.MidpointRounding 全部All
System.Net.WebUtilitySystem.Net.WebUtility 全部All
System.NullableSystem.Nullable 全部All
System.RandomSystem.Random 全部All
System.SByteSystem.SByte 全部All
System.Security.Cryptography.AsymmetricAlgorithmSystem.Security.Cryptography.AsymmetricAlgorithm 全部All
System.Security.Cryptography.CipherModeSystem.Security.Cryptography.CipherMode 全部All
System.Security.Cryptography.HashAlgorithmSystem.Security.Cryptography.HashAlgorithm 全部All
System.Security.Cryptography.HashAlgorithmNameSystem.Security.Cryptography.HashAlgorithmName 全部All
System.Security.Cryptography.HMACSystem.Security.Cryptography.HMAC 全部All
System.Security.Cryptography.HMACMD5System.Security.Cryptography.HMACMD5 全部All
System.Security.Cryptography.HMACSHA1System.Security.Cryptography.HMACSHA1 全部All
System.Security.Cryptography.HMACSHA256System.Security.Cryptography.HMACSHA256 全部All
System.Security.Cryptography.HMACSHA384System.Security.Cryptography.HMACSHA384 全部All
System.Security.Cryptography.HMACSHA512System.Security.Cryptography.HMACSHA512 全部All
System.Security.Cryptography.KeyedHashAlgorithmSystem.Security.Cryptography.KeyedHashAlgorithm 全部All
System.Security.Cryptography.MD5System.Security.Cryptography.MD5 全部All
System.Security.Cryptography.OidSystem.Security.Cryptography.Oid 全部All
System.Security.Cryptography.PaddingModeSystem.Security.Cryptography.PaddingMode 全部All
System.Security.Cryptography.RNGCryptoServiceProviderSystem.Security.Cryptography.RNGCryptoServiceProvider 全部All
System.Security.Cryptography.RSASystem.Security.Cryptography.RSA 全部All
System.Security.Cryptography.RSAEncryptionPaddingSystem.Security.Cryptography.RSAEncryptionPadding 全部All
System.Security.Cryptography.RSASignaturePaddingSystem.Security.Cryptography.RSASignaturePadding 全部All
System.Security.Cryptography.SHA1System.Security.Cryptography.SHA1 全部All
System.Security.Cryptography.SHA1ManagedSystem.Security.Cryptography.SHA1Managed 全部All
System.Security.Cryptography.SHA256System.Security.Cryptography.SHA256 全部All
System.Security.Cryptography.SHA256ManagedSystem.Security.Cryptography.SHA256Managed 全部All
System.Security.Cryptography.SHA384System.Security.Cryptography.SHA384 全部All
System.Security.Cryptography.SHA384ManagedSystem.Security.Cryptography.SHA384Managed 全部All
System.Security.Cryptography.SHA512System.Security.Cryptography.SHA512 全部All
System.Security.Cryptography.SHA512ManagedSystem.Security.Cryptography.SHA512Managed 全部All
System.Security.Cryptography.SymmetricAlgorithmSystem.Security.Cryptography.SymmetricAlgorithm 全部All
System.Security.Cryptography.X509Certificates.PublicKeySystem.Security.Cryptography.X509Certificates.PublicKey 全部All
System.Security.Cryptography.X509Certificates.RSACertificateExtensionsSystem.Security.Cryptography.X509Certificates.RSACertificateExtensions 全部All
System.Security.Cryptography.X509Certificates.X500DistinguishedNameSystem.Security.Cryptography.X509Certificates.X500DistinguishedName NameName
System.Security.Cryptography.X509Certificates.X509CertificateSystem.Security.Cryptography.X509Certificates.X509Certificate 全部All
System.Security.Cryptography.X509Certificates.X509Certificate2System.Security.Cryptography.X509Certificates.X509Certificate2 全部All
System.Security.Cryptography.X509Certificates.X509ContentTypeSystem.Security.Cryptography.X509Certificates.X509ContentType 全部All
System.Security.Cryptography.X509Certificates.X509NameTypeSystem.Security.Cryptography.X509Certificates.X509NameType 全部All
System.SingleSystem.Single 全部All
System.StringSystem.String 全部All
System.StringComparerSystem.StringComparer 全部All
System.StringComparisonSystem.StringComparison 全部All
System.StringSplitOptionsSystem.StringSplitOptions 全部All
System.Text.EncodingSystem.Text.Encoding 全部All
System.Text.RegularExpressions.CaptureSystem.Text.RegularExpressions.Capture Index、Length、ValueIndex, Length, Value
System.Text.RegularExpressions.CaptureCollectionSystem.Text.RegularExpressions.CaptureCollection Count、ItemCount, Item
System.Text.RegularExpressions.GroupSystem.Text.RegularExpressions.Group Captures、SuccessCaptures, Success
System.Text.RegularExpressions.GroupCollectionSystem.Text.RegularExpressions.GroupCollection Count、ItemCount, Item
System.Text.RegularExpressions.MatchSystem.Text.RegularExpressions.Match Empty、Groups、ResultEmpty, Groups, Result
System.Text.RegularExpressions.RegexSystem.Text.RegularExpressions.Regex (构造函数)、IsMatch、Match、Matches、Replace、Unescape、Split(Constructor), IsMatch, Match, Matches, Replace, Unescape, Split
System.Text.RegularExpressions.RegexOptionsSystem.Text.RegularExpressions.RegexOptions 全部All
System.Text.StringBuilderSystem.Text.StringBuilder 全部All
System.TimeSpanSystem.TimeSpan 全部All
System.TimeZoneSystem.TimeZone 全部All
System.TimeZoneInfo.AdjustmentRuleSystem.TimeZoneInfo.AdjustmentRule 全部All
System.TimeZoneInfo.TransitionTimeSystem.TimeZoneInfo.TransitionTime 全部All
System.TimeZoneInfoSystem.TimeZoneInfo 全部All
System.TupleSystem.Tuple 全部All
System.UInt16System.UInt16 全部All
System.UInt32System.UInt32 全部All
System.UInt64System.UInt64 全部All
System.UriSystem.Uri 全部All
System.UriPartialSystem.UriPartial 全部All
System.Xml.Linq.ExtensionsSystem.Xml.Linq.Extensions 全部All
System.Xml.Linq.XAttributeSystem.Xml.Linq.XAttribute 全部All
System.Xml.Linq.XCDataSystem.Xml.Linq.XCData 全部All
System.Xml.Linq.XCommentSystem.Xml.Linq.XComment 全部All
System.Xml.Linq.XContainerSystem.Xml.Linq.XContainer 全部All
System.Xml.Linq.XDeclarationSystem.Xml.Linq.XDeclaration 全部All
System.Xml.Linq.XDocumentSystem.Xml.Linq.XDocument 全部,除了:加载All, except of: Load
System.Xml.Linq.XDocumentTypeSystem.Xml.Linq.XDocumentType 全部All
System.Xml.Linq.XElementSystem.Xml.Linq.XElement 全部All
System.Xml.Linq.XNameSystem.Xml.Linq.XName 全部All
System.Xml.Linq.XNamespaceSystem.Xml.Linq.XNamespace 全部All
System.Xml.Linq.XNodeSystem.Xml.Linq.XNode 全部All
System.Xml.Linq.XNodeDocumentOrderComparerSystem.Xml.Linq.XNodeDocumentOrderComparer 全部All
System.Xml.Linq.XNodeEqualityComparerSystem.Xml.Linq.XNodeEqualityComparer 全部All
System.Xml.Linq.XObjectSystem.Xml.Linq.XObject 全部All
System.Xml.Linq.XProcessingInstructionSystem.Xml.Linq.XProcessingInstruction 全部All
System.Xml.Linq.XTextSystem.Xml.Linq.XText 全部All
System.Xml.XmlNodeTypeSystem.Xml.XmlNodeType 全部All

上下文变量Context variable

在每个策略表达式中均可隐式使用名为 context 的变量。A variable named context is implicitly available in every policy expression. 其成员提供与 \request 相关的信息。Its members provide information pertinent to the \request. 所有 context 成员均为只读的。All of the context members are read-only.

上下文变量Context Variable 允许的方法、属性和参数值Allowed methods, properties, and parameter values
上下文context ApiIApiApi: IApi

部署Deployment

Elapsed:TimeSpan - 时间戳值和当前时间之间的时间间隔Elapsed: TimeSpan - time interval between the value of Timestamp and current time

LastErrorLastError

操作Operation

产品Product

请求Request

RequestId:Guid - 唯一请求标识符RequestId: Guid - unique request identifier

响应Response

订阅Subscription

时间戳:DateTime - 接收到请求的时间点Timestamp: DateTime - point in time when request was received

Tracing: bool - 指示跟踪是为打开还是关闭Tracing: bool - indicates if tracing is on or off

UserUser

变量:IReadOnlyDictionary<string, object>Variables: IReadOnlyDictionary<string, object>

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

IsCurrentRevision:boolIsCurrentRevision: bool

Name:stringName: string

Path:stringPath: string

Revision: stringRevision: string

ServiceUrl:IUrlServiceUrl: IUrl

Version: stringVersion: string
context.Deploymentcontext.Deployment Region:stringRegion: string

ServiceName:stringServiceName: string

证书:IReadOnlyDictionary<string, X509Certificate2>Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.LastErrorcontext.LastError Source:stringSource: string

Reason:stringReason: string

Message:stringMessage: string

Scope:stringScope: string

Section:stringSection: string

Path:stringPath: string

PolicyId:stringPolicyId: string

有关 context.LastError 的详细信息,请参阅错误处理For more information about context.LastError, see Error handling.
context.Operationcontext.Operation Id:stringId: string

Method: 字符串Method: string

Name:stringName: string

UrlTemplate:stringUrlTemplate: string
context.Productcontext.Product Api:IEnumerable<IApi>Apis: IEnumerable<IApi>

ApprovalRequired:boolApprovalRequired: bool

组:IEnumerable<IGroup>Groups: IEnumerable<IGroup>

Id:stringId: string

Name:stringName: string

State:enum ProductState {NotPublished, Published}State: enum ProductState {NotPublished, Published}

SubscriptionLimit:int?SubscriptionLimit: int?

SubscriptionRequired:boolSubscriptionRequired: bool
context.Requestcontext.Request 正文:IMessageBodynull(如果请求没有正文)。Body: IMessageBody or null if request does not have a body.

证书:System.Security.Cryptography.X509Certificates.X509Certificate2Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

标头:IReadOnlyDictionary<string, string[]>Headers: IReadOnlyDictionary<string, string[]>

IpAddress:stringIpAddress: string

MatchedParameters:IReadOnlyDictionary<string, string>MatchedParameters: IReadOnlyDictionary<string, string>

Method:stringMethod: string

OriginalUrl:IUrlOriginalUrl: IUrl

URL:IUrlUrl: IUrl
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string)string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName:stringheaderName: string

defaultValue:stringdefaultValue: string

如果找不到标头,则返回逗号分隔的请求标头值或 defaultValueReturns comma-separated request header values or defaultValue if the header is not found.
context.Responsecontext.Response 正文:IMessageBodyBody: IMessageBody

标头:IReadOnlyDictionary<string, string[]>Headers: IReadOnlyDictionary<string, string[]>

StatusCode:intStatusCode: int

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

defaultValue:stringdefaultValue: string

如果找不到标头,则返回逗号分隔的响应标头值或 defaultValueReturns comma-separated response header values or defaultValue if the header is not found.
context.Subscriptioncontext.Subscription CreatedTime:DateTimeCreatedTime: DateTime

EndDate:DateTime?EndDate: DateTime?

Id:stringId: string

Key:stringKey: string

Name:stringName: string

PrimaryKey:stringPrimaryKey: string

SecondaryKey:stringSecondaryKey: string

StartDate:DateTime?StartDate: DateTime?
context.Usercontext.User Email:stringEmail: string

FirstName:stringFirstName: string

组:IEnumerable<IGroup>Groups: IEnumerable<IGroup>

Id:stringId: string

标识:IEnumerable<IUserIdentity>Identities: IEnumerable<IUserIdentity>

LastName:stringLastName: string

Note:stringNote: string

RegistrationDate:DateTimeRegistrationDate: DateTime
IApiIApi Id:stringId: string

Name:stringName: string

Path:stringPath: string

协议:IEnumerable<string>Protocols: IEnumerable<string>

ServiceUrl:IUrlServiceUrl: IUrl

SubscriptionKeyParameterNames:ISubscriptionKeyParameterNamesSubscriptionKeyParameterNames: ISubscriptionKeyParameterNames
IGroupIGroup Id:stringId: string

Name:stringName: string
IMessageBodyIMessageBody As<T>(preserveContent: bool = false):其中 T 为 string、byte[]、JObject、JToken、JArray、XNode、XElement、XDocumentAs<T>(preserveContent: bool = false): Where T: string, byte[],JObject, JToken, JArray, XNode, XElement, XDocument

context.Request.Body.As<T>context.Response.Body.As<T> 方法用于以指定的类型 T 读取请求和响应消息正文。The context.Request.Body.As<T> and context.Response.Body.As<T> methods are used to read a request and response message bodies in a specified type T. 该方法默认使用原始消息正文流,并在返回后将其呈现为不可用。By default the method uses the original message body stream and renders it unavailable after it returns. 要通过让该方法在正文流的副本上执行操作而避免这种情况,请将 preserveContent 参数设置为 trueTo avoid that by having the method operate on a copy of the body stream, set the preserveContent parameter to true. 请转到此处查看示例。Go here to see an example.
IUrlIUrl Host:stringHost: string

Path:stringPath: string

Port:intPort: int

查询:IReadOnlyDictionary<string, string[]>Query: IReadOnlyDictionary<string, string[]>

QueryString:stringQueryString: string

Scheme:stringScheme: string
IUserIdentityIUserIdentity Id:stringId: string

Provider:stringProvider: string
ISubscriptionKeyParameterNamesISubscriptionKeyParameterNames Header:stringHeader: string

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

defaultValue:stringdefaultValue: string

如果找不到参数,则会返回逗号分隔的查询参数值或 defaultValueReturns comma-separated query parameter values or defaultValue if the parameter is not found.
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue:T)T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) variableName:stringvariableName: string

defaultValue:TdefaultValue: T

如果找不到变量,则会返回强制转换为 TdefaultValue 类型的变量值。Returns variable value cast to type T or defaultValue if the variable is not found.

如果指定的类型与已返回变量的实际类型不符,此方法会引发异常。This method throws an exception if the specified type does not match the actual type of the returned variable.
BasicAuthCredentials AsBasic(input:this string)BasicAuthCredentials AsBasic(input: this string) input:stringinput: string

如果输入参数包含有效的 HTTP Basic Authentication 授权请求标头值,此方法会返回类型为 BasicAuthCredentials 的对象;否则,此方法会返回 null。If the input parameter contains a valid HTTP Basic Authentication authorization request header value, the method returns an object of type BasicAuthCredentials; otherwise the method returns null.
bool TryParseBasic(input:this string, result:out BasicAuthCredentials)bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input:stringinput: string

result:out BasicAuthCredentialsresult: out BasicAuthCredentials

如果输入参数包含请求标头中的有效 HTTP Basic Authentication 授权值,此方法会返回 true 且结果参数会包含类型为 BasicAuthCredentials 的值;否则,此方法会返回 falseIf the input parameter contains a valid HTTP Basic Authentication authorization value in the request header the method returns true and the result parameter contains a value of type BasicAuthCredentials; otherwise the method returns false.
BasicAuthCredentialsBasicAuthCredentials Password:stringPassword: string

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

如果输入参数包含有效的 JWT 令牌值,此方法会返回类型为 Jwt 的对象;否则,此方法会返回 nullIf the input parameter contains a valid JWT token value, the method returns an object of type Jwt; otherwise the method returns null.
bool TryParseJwt(input:this string, result:out Jwt)bool TryParseJwt(input: this string, result: out Jwt) input:stringinput: string

result:out Jwtresult: out Jwt

如果输入参数包含有效的 JWT 令牌值,此方法会返回 true 且结果参数包含类型为 Jwt 的值;否则,此方法会返回 falseIf the input parameter contains a valid JWT token value, the method returns true and the result parameter contains a value of type Jwt; otherwise the method returns false.
JwtJwt Algorithm:stringAlgorithm: string

受众:IEnumerable<string>Audience: IEnumerable<string>

声明:IReadOnlyDictionary<string, string[]>Claims: IReadOnlyDictionary<string, string[]>

ExpirationTime:DateTime?ExpirationTime: DateTime?

Id:stringId: string

Issuer:stringIssuer: string

IssuedAt:DateTime?IssuedAt: DateTime?

NotBefore:DateTime?NotBefore: DateTime?

Subject:stringSubject: string

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

defaultValue:stringdefaultValue: string

如果找不到标头,则返回逗号分隔的声明值或 defaultValueReturns comma-separated claim values or defaultValue if the header is not found.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[])byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - 要加密的明文input - plaintext to be encrypted

alg - 对称加密算法的名称alg - name of a symmetric encryption algorithm

key - 加密密钥key - encryption key

iv - 初始化矢量iv - initialization vector

返回已加密的明文。Returns encrypted plaintext.
byte[] Encrypt(input: this byte[], alg:System.Security.Cryptography.SymmetricAlgorithm)byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - 要加密的明文input - plaintext to be encrypted

alg - 加密算法alg - encryption algorithm

返回已加密的明文。Returns encrypted plaintext.
byte[] Encrypt(input: this byte[], alg:System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[])byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - 要加密的明文input - plaintext to be encrypted

alg - 加密算法alg - encryption algorithm

key - 加密密钥key - encryption key

iv - 初始化矢量iv - initialization vector

返回已加密的明文。Returns encrypted plaintext.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[])byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - 要解密的密文input - cypher text to be decrypted

alg - 对称加密算法的名称alg - name of a symmetric encryption algorithm

key - 加密密钥key - encryption key

iv - 初始化矢量iv - initialization vector

返回明文。Returns plaintext.
byte[] Decrypt(input: this byte[], alg:System.Security.Cryptography.SymmetricAlgorithm)byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - 要解密的密文input - cypher text to be decrypted

alg - 加密算法alg - encryption algorithm

返回明文。Returns plaintext.
byte[] Decrypt(input: this byte[], alg:System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[])byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - 要解密的密文input - cypher text to be decrypted

alg - 加密算法alg - encryption algorithm

key - 加密密钥key - encryption key

iv - 初始化矢量iv - initialization vector

返回明文。Returns plaintext.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2)bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) 在不检查证书吊销状态的情况下执行 X.509 链验证。Performs a X.509 chain validation without checking certificate revocation status.

输入 - 证书对象input - certificate object

如果验证成功,则返回 true;如果验证失败,则返回 falseReturns true if the validation succeeds; false if the validation fails.

后续步骤Next steps

有关如何使用策略的详细信息,请参阅:For more information working with policies, see: