Compartir a través de


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

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

Usuario

Variables: IReadOnlyDictionary<string, object>

void Trace(message: string)

Workspace
context.Api Id: string

IsCurrentRevision: bool

Name: string

Path: string

Revision: string

ServiceUrl: IUrl

Version: string
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
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
context.Workspace Id: string

Name: string
IApi Id: string

Name: string

Path: string

Protocols: IEnumerable<string>

ServiceUrl: IUrl

SubscriptionKeyParameterNames: ISubscriptionKeyParameterNames
IGraphQLDataObject Por determinar

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
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 JWT válido, el método devuelve un objeto de tipo Jwt; de lo 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 JWT válido, el método devuelve true y el parámetro de resultado contiene un valor de tipo Jwt; de lo 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.
  • Consulte cómo usar el seguimiento de API 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.