Espressioni di criteri di Gestione API

SI APPLICA A: Tutti i livelli di Gestione API

Questo articolo illustra la sintassi delle espressioni di criteri in C# 7. Ogni espressione ha accesso a:

  • La variabile di contesto specificata in modo implicito.
  • Un subset consentito di tipi .NET Framework.

Sintassi

  • Espressioni a istruzione singola:
    • Racchiuse in @(expression), dove expression è un'istruzione di espressione C# ben formata.
  • Espressioni a istruzioni multiple:
    • Racchiuse in @{expression}.
    • Tutti i percorsi di codice all'interno di espressioni a più istruzioni devono terminare con un'istruzione return.

Esempi

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

}

Utilizzo

A meno che nel riferimento ai criteri non sia specificato diversamente, le espressioni possono essere usate come valori di attributo o valori di testo in tutti i criteri di Gestione API.

Importante

Quando il criterio è definito, le espressioni dei criteri hanno solo una verifica limitata. Le espressioni vengono eseguite dal gateway in fase di esecuzione. Qualsiasi eccezione generata dalle espressioni dei criteri comporta un errore di runtime.

Tipi di .NET Framework consentiti nelle espressioni di criteri

Nella tabella seguente sono elencati i tipi di .NET Framework e i relativi membri consentiti nelle espressioni di criteri.

Type Membri supportati
Newtonsoft.Json.Formatting Tutte le date
Newtonsoft.Json.JsonConvert SerializeObject, DeserializeObject
Newtonsoft.Json.Linq.Extensions Tutte le date
Newtonsoft.Json.Linq.JArray Tutte le date
Newtonsoft.Json.Linq.JConstructor Tutte le date
Newtonsoft.Json.Linq.JContainer Tutte le date
Newtonsoft.Json.Linq.JObject Tutte le date
Newtonsoft.Json.Linq.JProperty Tutte le date
Newtonsoft.Json.Linq.JRaw Tutte le date
Newtonsoft.Json.Linq.JToken Tutte le date
Newtonsoft.Json.Linq.JTokenType Tutte le date
Newtonsoft.Json.Linq.JValue Tutte le date
System.Array Tutte le date
System.BitConverter Tutte le date
System.Boolean Tutte le date
System.Byte Tutte le date
System.Char Tutte le date
System.Collections.Generic.Dictionary<TKey, TValue> Tutte le date
System.Collections.Generic.HashSet<T> Tutte le date
System.Collections.Generic.ICollection<T> Tutte le date
System.Collections.Generic.IDictionary<TKey, TValue> Tutte le date
System.Collections.Generic.IEnumerable<T> Tutte le date
System.Collections.Generic.IEnumerator<T> Tutte le date
System.Collections.Generic.IList<T> Tutte le date
System.Collections.Generic.IReadOnlyCollection<T> Tutte le date
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> Tutte le date
System.Collections.Generic.ISet<T> Tutte le date
System.Collections.Generic.KeyValuePair<TKey, TValue> Tutte le date
System.Collections.Generic.List<T> Tutte le date
System.Collections.Generic.Queue<T> Tutte le date
System.Collections.Generic.Stack<T> Tutte le date
System.Convert Tutte le date
System.DateTime (Costruttore), 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 Tutte le date
System.Decimal Tutte le date
System.Double Tutte le date
System.Enum Parse, TryParse, ToString
System.Exception Tutte le date
System.Guid Tutte le date
System.Int16 Tutte le date
System.Int32 Tutte le date
System.Int64 Tutte le date
System.IO.StringReader Tutte le date
System.IO.StringWriter Tutte le date
System.Linq.Enumerable Tutte le date
System.Math Tutte le date
System.MidpointRounding Tutte le date
System.Net.IPAddress AddressFamily, Equals, GetAddressBytes, IsLoopbackParse, , TryParseToString
System.Net.WebUtility Tutte le date
System.Nullable Tutte le date
System.Random Tutte le date
System.SByte Tutte le date
System.Security.Cryptography.AsymmetricAlgorithm Tutte le date
System.Security.Cryptography.CipherMode Tutte le date
System.Security.Cryptography.HashAlgorithm Tutte le date
System.Security.Cryptography.HashAlgorithmName Tutte le date
System.Security.Cryptography.HMAC Tutte le date
System.Security.Cryptography.HMACMD5 Tutte le date
System.Security.Cryptography.HMACSHA1 Tutte le date
System.Security.Cryptography.HMACSHA256 Tutte le date
System.Security.Cryptography.HMACSHA384 Tutte le date
System.Security.Cryptography.HMACSHA512 Tutte le date
System.Security.Cryptography.KeyedHashAlgorithm Tutte le date
System.Security.Cryptography.MD5 Tutte le date
System.Security.Cryptography.Oid Tutte le date
System.Security.Cryptography.PaddingMode Tutte le date
System.Security.Cryptography.RNGCryptoServiceProvider Tutte le date
System.Security.Cryptography.RSA Tutte le date
System.Security.Cryptography.RSAEncryptionPadding Tutte le date
System.Security.Cryptography.RSASignaturePadding Tutte le date
System.Security.Cryptography.SHA1 Tutte le date
System.Security.Cryptography.SHA1Managed Tutte le date
System.Security.Cryptography.SHA256 Tutte le date
System.Security.Cryptography.SHA256Managed Tutte le date
System.Security.Cryptography.SHA384 Tutte le date
System.Security.Cryptography.SHA384Managed Tutte le date
System.Security.Cryptography.SHA512 Tutte le date
System.Security.Cryptography.SHA512Managed Tutte le date
System.Security.Cryptography.SymmetricAlgorithm Tutte le date
System.Security.Cryptography.X509Certificates.PublicKey Tutte le date
System.Security.Cryptography.X509Certificates.RSACertificateExtensions Tutte le date
System.Security.Cryptography.X509Certificates.X500DistinguishedName Name
System.Security.Cryptography.X509Certificates.X509Certificate Tutte le date
System.Security.Cryptography.X509Certificates.X509Certificate2 Tutte le date
System.Security.Cryptography.X509Certificates.X509ContentType Tutte le date
System.Security.Cryptography.X509Certificates.X509NameType Tutte le date
System.Single Tutte le date
System.String Tutte le date
System.StringComparer Tutte le date
System.StringComparison Tutte le date
System.StringSplitOptions Tutte le date
System.Text.Encoding Tutte le date
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 (Costruttore), IsMatch, Match, Matches, Replace, Unescape, Split
System.Text.RegularExpressions.RegexOptions Tutte le date
System.Text.StringBuilder Tutte le date
System.TimeSpan Tutte le date
System.TimeZone Tutte le date
System.TimeZoneInfo.AdjustmentRule Tutte le date
System.TimeZoneInfo.TransitionTime Tutte le date
System.TimeZoneInfo Tutte le date
System.Tuple Tutte le date
System.UInt16 Tutte le date
System.UInt32 Tutte le date
System.UInt64 Tutte le date
System.Uri Tutte le date
System.UriPartial Tutte le date
System.Xml.Linq.Extensions Tutte le date
System.Xml.Linq.XAttribute Tutte le date
System.Xml.Linq.XCData Tutte le date
System.Xml.Linq.XComment Tutte le date
System.Xml.Linq.XContainer Tutte le date
System.Xml.Linq.XDeclaration Tutte le date
System.Xml.Linq.XDocument Tutti tranne Load
System.Xml.Linq.XDocumentType Tutte le date
System.Xml.Linq.XElement Tutte le date
System.Xml.Linq.XName Tutte le date
System.Xml.Linq.XNamespace Tutte le date
System.Xml.Linq.XNode Tutte le date
System.Xml.Linq.XNodeDocumentOrderComparer Tutte le date
System.Xml.Linq.XNodeEqualityComparer Tutte le date
System.Xml.Linq.XObject Tutte le date
System.Xml.Linq.XProcessingInstruction Tutte le date
System.Xml.Linq.XText Tutte le date
System.Xml.XmlNodeType Tutte le date

Variabile di contesto

La variabile context è disponibile in modo implicito in ogni espressione di criteri. I relativi membri:

  • Specificano informazioni pertinenti alla richiesta e alla risposta dell'API e alle proprietà correlate.
  • Sono tutti di sola lettura.
Variabile di contesto Metodi, proprietà e valori di parametro consentiti
context Api: IApi

Deployment

Scaduto: TimeSpan: intervallo di tempo tra il valore di Timestamp e l'ora corrente

GraphQL

LastError

Operation

Request

RequestId: Guid: identificatore univoco della richiesta

Response

Subscription

Timestamp: DateTime: data/ora di ricezione della richiesta

Tracing: bool: indica se la funzionalità di traccia è attiva o disattiva

Utente

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 (restituisce "gestito" per i gateway gestiti)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (restituisce "gestito" per i gateway gestiti)

InstanceId: string (restituisce "gestito" per i gateway gestiti)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Esempi
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

Per ulteriori informazioni su context.LastError vedere Gestione degli errori.
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 o null se la richiesta non ha un corpo.

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: IPrivateEndpointConnection o null se la richiesta non proviene da una connessione di endpoint privato.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Restituisce valori di intestazione di richiesta separati da virgole oppure defaultValue se non viene trovata l'intestazione.
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

Restituisce valori di intestazione di risposta separati da virgole oppure defaultValue se non viene trovata l'intestazione.
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 Da definire

IGroup Id: string

Name: string
IMessageBody As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument

- I metodi context.Request.Body.As<T> e context.Response.Body.As<T> leggono il corpo di un messaggio di richiesta o risposta nel tipo specificato T.

oppure

AsFormUrlEncodedContent(bool preserveContent = false)

- I metodi context.Request.Body.AsFormUrlEncodedContent() e context.Response.Body.AsFormUrlEncodedContent() leggono i dati del modulo codificati con URL in un corpo del messaggio di richiesta o risposta e restituiscono un oggetto IDictionary<string, IList<string>. L'oggetto decodificato supporta operazioni IDictionary e le espressioni seguenti: ToQueryString(), JsonConvert.SerializeObject(), ToFormUrlEncodedContent().

Per impostazione predefinita, i metodi As<T> e AsFormUrlEncodedContent():
  • Usano il flusso del corpo del messaggio originale.
  • Lo rendono non disponibile dopo la restituzione.

Per evitare che il metodo funzioni su una copia del flusso del corpo, impostare il parametro preserveContent su true, come illustrato negli esempi per il criterio set-body.
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

Per ulteriori informazioni, vedere l'API REST.
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

Restituisce valori di parametro separati da virgole oppure defaultValue se il parametro non viene trovato.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

Name: string
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) variableName: string

defaultValue: T

Restituisce il valore della variabile nel tipo T oppure defaultValue se la variabile non viene trovata.

Questo metodo genera un'eccezione se il tipo specificato non corrisponde al tipo effettivo della variabile restituita.
BasicAuthCredentials AsBasic(input: this string) input: string

Se il parametro di input contiene un valore di intestazione di richiesta di autorizzazione Autenticazione HTTP di base valido, il metodo restituisce un oggetto di tipo BasicAuthCredentials; in caso contrario restituisce un valore null.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Se il parametro di input contiene un valore di autorizzazione di Autenticazione HTTP di base valido nell'intestazione della richiesta, il metodo restituisce true e il parametro risultante contiene un valore di tipo BasicAuthCredentials; in caso contrario, il metodo restituisce false.
BasicAuthCredentials Password: string

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

Se il parametro di input contiene un valore di token JWT valido, il metodo restituisce un oggetto di tipo Jwt; in caso contrario restituisce null.
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Se il parametro di input contiene un valore di token JWT valido, il metodo restituisce true e il parametro del risultato contiene un valore di tipo Jwt; in caso contrario il metodo restituisce 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

Restituisce valori di attestazione separati da virgole oppure defaultValue se non viene trovata l'intestazione.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input: testo non crittografato da crittografare

alg: nome di un algoritmo di crittografia simmetrica

key: chiave di crittografia

iv: vettore di inizializzazione

Restituisce testo normale crittografato.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input: testo non crittografato da crittografare

alg: algoritmo di crittografia

Restituisce testo normale crittografato.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input: testo non crittografato da crittografare

alg: algoritmo di crittografia

key: chiave di crittografia

iv: vettore di inizializzazione

Restituisce testo normale crittografato.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input: testo cifrato da decrittografare

alg: nome di un algoritmo di crittografia simmetrica

key: chiave di crittografia

iv: vettore di inizializzazione

Restituisce testo normale non crittografato.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input: testo cifrato da decrittografare

alg: algoritmo di crittografia

Restituisce testo normale non crittografato.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input: testo cifrato da decrittografare

alg: algoritmo di crittografia

key: chiave di crittografia

iv: vettore di inizializzazione

Restituisce testo normale non crittografato.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) Esegue una convalida della catena X.509 senza controllare lo stato di revoca dei certificati.

input: oggetto del certificato

Restituisce true se la convalida ha esito positivo; false se la convalida non riesce.

Per altre informazioni sull'uso di questi criteri, vedere:

Per altre informazioni:

  • Vedere la procedura per fornire informazioni di contesto al servizio back-end. Per fornire queste informazioni, usare i criteri per l'impostazione del parametro di stringa di query e l'impostazione dell'intestazione HTTP.
  • Vedere la procedura per usare i criteri di convalida JWT per preautorizzare l'accesso alle operazioni in base alle attestazioni dei token.
  • Vedere la procedura per usare una traccia di Controllo API per visualizzare il modo in cui i criteri vengono valutati e i risultati delle valutazioni.
  • Vedere la procedura per usare le espressioni con i criteri di recupero dalla cache e di archiviazione nella cache per configurare la memorizzazione delle risposte nella cache di Gestione API. Impostare la durata corrispondente alla memorizzazione delle risposte nella cache del servizio back-end, come specificato dalla direttiva Cache-Control del servizio.
  • Vedere la procedura per eseguire operazioni di filtro dei contenuti. Rimuovere elementi dati dalla risposta ricevuta dal servizio back-end usando i criteri di controllo del flusso e impostazione del corpo.
  • Per scaricare gli esempi dei criteri, vedere il repository GitHub api-management-samples/policies.