Expresiones de las directivas de API Management

SE APLICA A: todos los niveles de API Management

En este artículo se describe la sintaxis de expresiones de directiva en C# 7. Cada expresión tiene acceso a:

  • La variable de contexto proporcionada implícitamente.
  • Un subconjunto permitido de tipos de .NET Framework.

Sintaxis

  • Expresiones de instrucción única:
    • Se incluyen en @(expression), donde expression es una instrucción de expresión bien formada de C#.
  • Expresiones con varias instrucciones:
    • Se incluyen en @{expression}.
    • Todas las rutas de código de las expresiones de múltiples declaraciones deben terminar con una declaración return.

Ejemplos

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

}

Uso

A menos que la referencia de la directiva especifique lo contrario, las expresiones pueden utilizarse como valores de atributos o valores de texto en cualquier directiva de API Management.

Importante

Cuando se define la directiva, las expresiones de la directiva solo tienen una comprobación limitada. La puerta de enlace ejecuta las expresiones en tiempo de ejecución. Las excepciones generadas por las expresiones de la directiva generan un error en tiempo de ejecución.

Tipos de .NET Framework permitidos en expresiones de directiva

En la tabla siguiente se enumeran los tipos de .NET Framework y los miembros que se permiten en las expresiones de directiva.

Tipo Miembros compatibles
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 Todos excepto 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

Variable de contexto

La variable context está disponible implícitamente en todas las expresiones de la directiva. Sus miembros:

  • Proporcionan información relevante para la solicitud y respuesta de la API y las propiedades relacionadas.
  • Son todos de solo lectura.
Variable de contexto Métodos, propiedades y valores de parámetro admitidos
context Api: IApi

Deployment

Transcurrido: TimeSpanintervalo de tiempo entre el valor de Timestamp y la hora actual

GraphQL

LastError

Operation

Request

RequestId: GuidIdentificador de solicitud único

Response

Subscription

Timestamp: DateTimepunto en el tiempo en que se recibió la solicitud

Tracing: boolindica si el seguimiento está activado o desactivado

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 (devuelve "managed" para las puerta de enlace administradas)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (devuelve "managed" para las puerta de enlace administradas)

InstanceId: string (devuelve "managed" para las puerta de enlace administradas)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Ejemplos
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

Para obtener más información sobre context.LastError, consulte Control de errores.
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 si la solicitud no tiene un cuerpo.

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 si la solicitud no viene de un punto de conexión privado.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Devuelve valores de encabezado de solicitud separados por comas o defaultValue si no se encuentra el encabezado.
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

Devuelve valores de encabezado de respuesta separados por comas o defaultValue si no se encuentra el encabezado.
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 TBD

IGroup Id: string

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

- Los métodos context.Request.Body.As<T> y context.Response.Body.As<T> leen un cuerpo de un mensaje de respuesta o solicitud en el tipo T especificado.

O bien

AsFormUrlEncodedContent(bool preserveContent = false)

- Los métodos context.Request.Body.AsFormUrlEncodedContent() y context.Response.Body.AsFormUrlEncodedContent() leen datos de formulario con codificación URL en un cuerpo de mensaje de solicitud o respuesta y devuelven un objeto IDictionary<string, IList<string>. El objeto descodificado admite operaciones IDictionary y las siguientes expresiones: ToQueryString(), JsonConvert.SerializeObject(), ToFormUrlEncodedContent().

De forma predeterminada, los métodos As<T> y AsFormUrlEncodedContent():
  • Use la secuencia del cuerpo del mensaje original.
  • Represéntela como no disponible después de que vuelva.

Para evitar este resultado haciendo que el método trabaje en una copia de la secuencia del cuerpo, establezca el parámetro preserveContent en true, como se muestra en los ejemplos para la directiva set-body.
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

Para más información, vea la API de 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

Devuelve valores de parámetro de consulta separados por comas o defaultValue si no se encuentra el parámetro.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

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

defaultValue: T

Devuelve el valor de la variable convertido al tipo T o defaultValue si no se encuentra la variable.

Este método produce una excepción si el tipo especificado no coincide con el tipo real de la variable devuelta.
BasicAuthCredentials AsBasic(input: this string) input: string

Si el parámetro de entrada contiene un valor válido de encabezado de solicitud de autorización de autenticación básica HTTP, el método devuelve un objeto de tipo BasicAuthCredentials; en caso contrario, el método devuelve nulo.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Si el parámetro de entrada contiene un valor válido de autorización de autenticación básica HTTP en el encabezado de solicitud, el método devuelve true y el parámetro de resultado contiene un valor del tipo BasicAuthCredentials; en caso contrario, el método devuelve false.
BasicAuthCredentials Password: string

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

Si el parámetro de entrada contiene un valor de token JWT válido, el método devuelve un objeto de tipo Jwt; en caso contrario, el método devuelve null.
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Si el parámetro de entrada contiene un valor de token JWT válido, el método devuelve true y el parámetro de resultado contiene un valor de tipo Jwt; en caso contrario, el método devuelve 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

Devuelve valores de notificación separados por comas o defaultValue i no se encuentra el encabezado.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input: texto no cifrado que se va a cifrar

alg: nombre de un algoritmo de cifrado simétrico

key: clave de cifrado

iv: vector de inicialización

Devuelve cifrado el texto no cifrado.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input: texto no cifrado que se va a cifrar

alg: algoritmo de cifrado

Devuelve cifrado el texto no cifrado.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input: texto no cifrado que se va a cifrar

alg: algoritmo de cifrado

key: clave de cifrado

iv: vector de inicialización

Devuelve cifrado el texto no cifrado.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input: texto cifrado que se va a descifrar

alg: nombre de un algoritmo de cifrado simétrico

key: clave de cifrado

iv: vector de inicialización

Devuelve texto no cifrado.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input: texto cifrado que se va a descifrar

alg: algoritmo de cifrado

Devuelve texto no cifrado.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input: texto cifrado que se va a descifrar

alg: algoritmo de cifrado

key: clave de cifrado

iv: vector de inicialización

Devuelve texto no cifrado.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) Realiza una validación de la cadena X.509 sin comprobar el estado de revocación de los certificados.

input: objeto del certificado

Devuelve true si la validación es correcta; false si hay un error.

Para obtener más información sobre cómo trabajar con directivas, consulte:

Para obtener más información:

  • Vea cómo proporcionar información de contexto al servicio back-end. Use las directivas Establecer el parámetro de cadena de consulta y Establecer encabezado HTTP para proporcionar esta información.
  • Vea cómo utilizar la directiva de validación de JWT para preautorizar el acceso a operaciones según notificaciones de token.
  • Vea la forma de usar un seguimiento de API Inspector para detectar cómo se evalúan las directivas y los resultados de esas evaluaciones.
  • Vea cómo usar expresiones con las directivas Obtener de caché y Almacenar en caché para configurar el almacenamiento en caché de la respuesta de API Management. Defina una duración que coincida con el almacenamiento en caché de la respuesta del servicio back-end especificado por la directiva Cache-Control del servicio back-end.
  • Vea cómo realizar el filtrado de contenido. Quite elementos de datos de la respuesta recibida desde el servicio back-end mediante las directivas Flujo de control y Establecer cuerpo.
  • Para descargar las declaraciones de directiva, vaya a api-management-samples/policies en el repositorio de GitHub.