This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Download Microsoft Edge
More info about Internet Explorer and Microsoft Edge
APPLIES TO: All API Management tiers
This article discusses policy expressions syntax in C# 7. Each expression has access to:
The implicitly provided
context
variable.
An allowed
subset
of .NET Framework types.
Syntax
Single statement expressions:
Enclosed in
@(expression)
, where
expression
is a well-formed C# expression statement.
Multi-statement expressions:
Enclosed in
@{expression}
.
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
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.
Supported members
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
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
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
(Constructor), 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
All, except 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 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
Api
: IApi
Deployment
Elapsed: TimeSpan
- time interval between the value of Timestamp
and current time
GraphQL
LastError
Operation
Request
RequestId
: Guid
- unique request identifier
Response
Subscription
Timestamp
: DateTime
- point in time when request was received
Tracing
: bool
- indicates if tracing is on or off
User
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
(returns 'managed' for managed gateways)
Region
: string
ServiceId
: string
ServiceName
: string
Certificates
: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway
Id
: string
(returns 'managed' for managed gateways)
InstanceId
: string
(returns 'managed' for managed gateways)
IsManaged
: bool
context.GraphQL
GraphQLArguments
: IGraphQLDataObject
Parent
: IGraphQLDataObject
Examples
context.LastError
Source
: string
Reason
: string
Message
: string
Scope
: string
Section
: string
Path
: string
PolicyId
: string
For more information about context.LastError
, see Error handling.
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
Body
: IMessageBody
or null
if request doesn't have a body.
Certificate
: System.Security.Cryptography.X509Certificates.X509Certificate2
Headers
: IReadOnlyDictionary<string, string[]>
IpAddress
: string
MatchedParameters
: IReadOnlyDictionary<string, string>
Method
: string
OriginalUrl
: IUrl
Url
: IUrl
PrivateEndpointConnection
: IPrivateEndpointConnection
or null
if request doesn't come from a private endpoint connection.
context.Response
Body
: IMessageBody
Headers
: IReadOnlyDictionary<string, string[]>
StatusCode
: int
StatusReason
: string
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
Id
: string
Name
: string
Path
: string
Protocols
: IEnumerable<string>
ServiceUrl
: IUrl
SubscriptionKeyParameterNames
: ISubscriptionKeyParameterNames
IGraphQLDataObject
IGroup
Id
: string
Name
: 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:
- Use the original message body stream.
- Render it unavailable after it returns.
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
: string
GroupId
: string
MemberName
: string
For more information, see the REST API.
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
Returns comma-separated query parameter values or defaultValue
if the parameter isn't found.
IUserIdentity
Id
: string
Provider
: string
IWorkspace
Id
: string
Name
: string
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T)
variableName
: string
defaultValue
: T
Returns 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
: string
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)
input
: string
result
: out BasicAuthCredentials
If 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
: string
UserId
: string
Jwt AsJwt(input: this string)
input
: string
If 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)
input
: string
result
: out Jwt
If 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
.
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
Returns 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 encrypted
alg
- name of a symmetric encryption algorithm
key
- encryption key
iv
- initialization vector
Returns encrypted plaintext.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm)
input
- plaintext to be encrypted
alg
- encryption algorithm
Returns encrypted plaintext.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[])
input
- plaintext to be encrypted
alg
- encryption algorithm
key
- encryption key
iv
- initialization vector
Returns encrypted plaintext.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[])
input
- cypher text to be decrypted
alg
- name of a symmetric encryption algorithm
key
- encryption key
iv
- initialization vector
Returns plaintext.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm)
input
- cypher text to be decrypted
alg
- encryption algorithm
Returns plaintext.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[])
input
- cypher text to be decrypted
alg
- encryption algorithm
key
- encryption key
iv
- initialization vector
Returns plaintext.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2)
Performs an X.509 chain validation without checking certificate revocation status.
input
- certificate object
Returns true
if the validation succeeds; false
if the validation fails.
Related content
For more information working with policies, see:
Policies in API Management
Tutorial: Transform and protect APIs
Policy reference for a full list of policy statements and their settings
Policy snippets repo
Author policies using Microsoft Copilot for Azure
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 an API Inspector trace 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-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.
To download the policy statements, see the api-management-samples/policies GitHub repo.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback.
Submit and view feedback for
This product