Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
APPLIES TO: All API Management tiers
This article discusses policy expressions syntax in C# 7. Each expression has access to:
Syntax
- Single statement expressions:
- Enclosed in
@(expression), whereexpressionis a well-formed C# expression statement.
- Enclosed in
- Multi-statement expressions:
- Enclosed in
@{expression}. - All code paths within multi-statement expressions must end with a
returnstatement.
- Enclosed in
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
Unless the policy reference specifies otherwise, expressions can be used as attribute values or text values in any API Management policy.
Important
When the policy is defined, policy expressions only have limited verification. Expressions are executed by the gateway at run-time. Any exceptions generated by policy expressions result in a runtime error.
.NET Framework types allowed in policy expressions
The following table lists the .NET Framework types and members allowed in policy expressions.
| Type | Supported members |
|---|---|
Newtonsoft.Json.Formatting |
All |
Newtonsoft.Json.JsonConvert |
SerializeObject, DeserializeObject |
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 |
(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.DateTimeKind |
Utc |
System.DateTimeOffset |
All |
System.Decimal |
All |
System.Double |
All |
System.Enum |
Parse, TryParse, ToString |
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 |
AddressFamily, Equals, GetAddressBytes, IsLoopback, Parse, TryParse, ToString |
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 |
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 |
(Constructor), IsMatch, Match, Matches, Replace, Unescape, Split |
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 |
All, except 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 variable
The context variable is implicitly available in every policy expression. Its members:
- Provide information relevant to the API request and response, and related properties.
- Are all read-only.
| Context Variable | Allowed methods, properties, and parameter values |
|---|---|
context |
Api: IApiDeploymentElapsed: TimeSpan - time interval between the value of Timestamp and current timeGraphQLLastErrorOperationRequestRequestId: Guid - unique request identifierResponseSubscriptionTimestamp: DateTime - point in time when request was receivedTracing: bool - indicates if tracing is on or off User Variables: IReadOnlyDictionary<string, object>void Trace(message: string) Workspace |
context.Api |
Id: stringIsCurrentRevision: boolName: stringPath: stringRevision: stringServiceUrl: IUrlVersion: string |
context.Deployment |
GatewayGatewayId: string (returns 'managed' for managed gateways)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id: string (returns 'managed' for managed gateways)InstanceId: string (returns 'managed' for managed gateways)IsManaged: bool |
context.Deployment.SustainabilityInfo |
CurrentCarbonIntensity: Enum CarbonIntensityCategory |
context.GraphQL |
GraphQLArguments: IGraphQLDataObjectParent: IGraphQLDataObjectExamples |
context.LastError |
Source: stringReason: stringMessage: stringScope: stringSection: stringPath: stringPolicyId: stringFor more information about context.LastError, see Error handling. |
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 or null if request doesn't have a body.Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2Headers: IReadOnlyDictionary<string, string[]>IpAddress: stringMatchedParameters: IReadOnlyDictionary<string, string>Method: stringOriginalUrl: IUrlUrl: IUrlPrivateEndpointConnection: IPrivateEndpointConnection or null if request doesn't come from a private endpoint connection. |
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringReturns comma-separated request header values or defaultValue if the header isn't found. |
context.Response |
Body: IMessageBodyHeaders: IReadOnlyDictionary<string, string[]>StatusCode: intStatusReason: string |
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringReturns comma-separated response header values or defaultValue if the header isn't found. |
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 |
TBD |
IGroup |
Id: stringName: string |
IMessageBody |
As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument - The context.Request.Body.As<T> and context.Response.Body.As<T> methods read a request or response message body in specified type T. - Or - AsFormUrlEncodedContent(bool preserveContent = false) - The context.Request.Body.AsFormUrlEncodedContent() and context.Response.Body.AsFormUrlEncodedContent() methods read URL-encoded form data in a request or response message body and return an IDictionary<string, IList<string> object. The decoded object supports IDictionary operations and the following expressions: ToQueryString(), JsonConvert.SerializeObject(), ToFormUrlEncodedContent(). By default, the As<T> and AsFormUrlEncodedContent() methods:
To avoid that and have the method operate on a copy of the body stream, set the preserveContent parameter to true, as shown in examples for the set-body policy. |
IPrivateEndpointConnection |
Name: stringGroupId: stringMemberName: stringFor more information, see the 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: stringReturns comma-separated query parameter values or defaultValue if the parameter isn't found. |
IUserIdentity |
Id: stringProvider: string |
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) |
variableName: stringdefaultValue: TReturns variable value cast to type T or defaultValue if the variable isn't found.This method throws an exception if the specified type doesn't match the actual type of the returned variable. |
BasicAuthCredentials AsBasic(input: this string) |
input: stringIf 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) |
input: stringresult: out BasicAuthCredentialsIf 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. |
BasicAuthCredentials |
Password: stringUserId: string |
Jwt AsJwt(input: this string) |
input: stringIf the input parameter contains a valid JWT value, the method returns an object of type Jwt; otherwise the method returns null. |
bool TryParseJwt(input: this string, result: out Jwt) |
input: stringresult: out JwtIf the input parameter contains a valid JWT value, the method returns true and the result parameter contains a value of type Jwt; otherwise the method returns 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: stringReturns comma-separated claim values or defaultValue if the header isn't found. |
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - plaintext to be encryptedalg - name of a symmetric encryption algorithmkey - encryption keyiv - initialization vectorReturns encrypted plaintext. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - plaintext to be encryptedalg - encryption algorithmReturns encrypted plaintext. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - plaintext to be encryptedalg - encryption algorithmkey - encryption keyiv - initialization vectorReturns encrypted plaintext. |
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - cypher text to be decryptedalg - name of a symmetric encryption algorithmkey - encryption keyiv - initialization vectorReturns plaintext. |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - cypher text to be decryptedalg - encryption algorithmReturns plaintext. |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - cypher text to be decryptedalg - encryption algorithmkey - encryption keyiv - initialization vectorReturns plaintext. |
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) |
Performs an X.509 chain validation without checking certificate revocation status.input - certificate objectReturns true if the validation succeeds; false if the validation fails. |
Related content
For more information about working with policies, see:
- Tutorial: Transform and protect your API
- Policy reference for a full list of policy statements and their settings
- Policy expressions
- Set or edit policies
- Reuse policy configurations
- Policy snippets repo
- Policy playground repo
- Azure API Management policy toolkit
- Get Copilot assistance to create, explain, and troubleshoot policies
For more information:
- See how to supply context information to your backend service. Use the Set query string parameter and Set HTTP header policies to supply this information.
- See how to use the Validate JWT policy to pre-authorize access to operations based on token claims.
- See how to use API tracing to detect how policies are evaluated and the results of those evaluations.
- See how to use expressions with the Get from cache and Store to cache policies to configure API Management response caching. Set a duration that matches the response caching of the backend service as specified by the backed service's
Cache-Controldirective. - See how to perform content filtering. Remove data elements from the response received from the backend using the Control flow and Set body policies.
- To download the policy statements, see the api-management-samples/policies GitHub repo.