Výrazy zásad služby API Management

PLATÍ PRO: Všechny úrovně služby API Management

Tento článek popisuje syntaxi výrazů zásad v jazyce C# 7. Každý výraz má přístup k:

Syntaxe

  • Výrazy s jedním příkazem:
    • Uzavřeno ve @(expression)výrazu c# ve správném formátu, kde expression je příkaz výrazu jazyka C#.
  • Výrazy s více příkazy:
    • Uzavřeno do @{expression}.
    • Všechny cesty kódu v rámci výrazů s více příkazy musí končit příkazem return .

Příklady

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

}

Využití

Pokud odkaz na zásadu neurčí jinak, výrazy se dají použít jako hodnoty atributů nebo textové hodnoty v jakékoli zásadě služby API Management.

Důležité

Pokud jsou definované zásady, výrazy zásad mají omezené možnosti ověřování. Brána spouští výrazy za běhu. Jakékoli výjimky vygenerované výrazy zásad způsobí chybu za běhu.

Typy rozhraní .NET Framework povolené ve výrazech zásad

Následující tabulka uvádí typy a členy rozhraní .NET Framework povolené ve výrazech zásad.

Typ Podporovaní členové
Newtonsoft.Json.Formatting Vše
Newtonsoft.Json.JsonConvert SerializeObject, DeserializeObject
Newtonsoft.Json.Linq.Extensions Vše
Newtonsoft.Json.Linq.JArray Vše
Newtonsoft.Json.Linq.JConstructor Vše
Newtonsoft.Json.Linq.JContainer Vše
Newtonsoft.Json.Linq.JObject Vše
Newtonsoft.Json.Linq.JProperty Vše
Newtonsoft.Json.Linq.JRaw Vše
Newtonsoft.Json.Linq.JToken Vše
Newtonsoft.Json.Linq.JTokenType Vše
Newtonsoft.Json.Linq.JValue Vše
System.Array Vše
System.BitConverter Vše
System.Boolean Vše
System.Byte Vše
System.Char Vše
System.Collections.Generic.Dictionary<TKey, TValue> Vše
System.Collections.Generic.HashSet<T> Vše
System.Collections.Generic.ICollection<T> Vše
System.Collections.Generic.IDictionary<TKey, TValue> Vše
System.Collections.Generic.IEnumerable<T> Vše
System.Collections.Generic.IEnumerator<T> Vše
System.Collections.Generic.IList<T> Vše
System.Collections.Generic.IReadOnlyCollection<T> Vše
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> Vše
System.Collections.Generic.ISet<T> Vše
System.Collections.Generic.KeyValuePair<TKey, TValue> Vše
System.Collections.Generic.List<T> Vše
System.Collections.Generic.Queue<T> Vše
System.Collections.Generic.Stack<T> Vše
System.Convert Vše
System.DateTime (Konstruktor), Add, AddDays, , AddMillisecondsAddTicksAddMinutesAddMonthsAddHoursAddSeconds, , AddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonthNowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear
System.DateTimeKind Utc
System.DateTimeOffset Vše
System.Decimal Vše
System.Double Vše
System.Enum Parse, , TryParseToString
System.Exception Vše
System.Guid Vše
System.Int16 Vše
System.Int32 Vše
System.Int64 Vše
System.IO.StringReader Vše
System.IO.StringWriter Vše
System.Linq.Enumerable Vše
System.Math Vše
System.MidpointRounding Vše
System.Net.IPAddress AddressFamily, Equals, GetAddressBytes, IsLoopback, Parse, , TryParseToString
System.Net.WebUtility Vše
System.Nullable Vše
System.Random Vše
System.SByte Vše
System.Security.Cryptography.AsymmetricAlgorithm Vše
System.Security.Cryptography.CipherMode Vše
System.Security.Cryptography.HashAlgorithm Vše
System.Security.Cryptography.HashAlgorithmName Vše
System.Security.Cryptography.HMAC Vše
System.Security.Cryptography.HMACMD5 Vše
System.Security.Cryptography.HMACSHA1 Vše
System.Security.Cryptography.HMACSHA256 Vše
System.Security.Cryptography.HMACSHA384 Vše
System.Security.Cryptography.HMACSHA512 Vše
System.Security.Cryptography.KeyedHashAlgorithm Vše
System.Security.Cryptography.MD5 Vše
System.Security.Cryptography.Oid Vše
System.Security.Cryptography.PaddingMode Vše
System.Security.Cryptography.RNGCryptoServiceProvider Vše
System.Security.Cryptography.RSA Vše
System.Security.Cryptography.RSAEncryptionPadding Vše
System.Security.Cryptography.RSASignaturePadding Vše
System.Security.Cryptography.SHA1 Vše
System.Security.Cryptography.SHA1Managed Vše
System.Security.Cryptography.SHA256 Vše
System.Security.Cryptography.SHA256Managed Vše
System.Security.Cryptography.SHA384 Vše
System.Security.Cryptography.SHA384Managed Vše
System.Security.Cryptography.SHA512 Vše
System.Security.Cryptography.SHA512Managed Vše
System.Security.Cryptography.SymmetricAlgorithm Vše
System.Security.Cryptography.X509Certificates.PublicKey Vše
System.Security.Cryptography.X509Certificates.RSACertificateExtensions Vše
System.Security.Cryptography.X509Certificates.X500DistinguishedName Name
System.Security.Cryptography.X509Certificates.X509Certificate Vše
System.Security.Cryptography.X509Certificates.X509Certificate2 Vše
System.Security.Cryptography.X509Certificates.X509ContentType Vše
System.Security.Cryptography.X509Certificates.X509NameType Vše
System.Single Vše
System.String Vše
System.StringComparer Vše
System.StringComparison Vše
System.StringSplitOptions Vše
System.Text.Encoding Vše
System.Text.RegularExpressions.Capture Index, , LengthValue
System.Text.RegularExpressions.CaptureCollection Count, Item
System.Text.RegularExpressions.Group Captures, Success
System.Text.RegularExpressions.GroupCollection Count, Item
System.Text.RegularExpressions.Match Empty, , GroupsResult
System.Text.RegularExpressions.Regex (konstruktor), IsMatch, Match, MatchesReplace, , UnescapeSplit
System.Text.RegularExpressions.RegexOptions Vše
System.Text.StringBuilder Vše
System.TimeSpan Vše
System.TimeZone Vše
System.TimeZoneInfo.AdjustmentRule Vše
System.TimeZoneInfo.TransitionTime Vše
System.TimeZoneInfo Vše
System.Tuple Vše
System.UInt16 Vše
System.UInt32 Vše
System.UInt64 Vše
System.Uri Vše
System.UriPartial Vše
System.Xml.Linq.Extensions Vše
System.Xml.Linq.XAttribute Vše
System.Xml.Linq.XCData Vše
System.Xml.Linq.XComment Vše
System.Xml.Linq.XContainer Vše
System.Xml.Linq.XDeclaration Vše
System.Xml.Linq.XDocument Vše, s výjimkou Load
System.Xml.Linq.XDocumentType Vše
System.Xml.Linq.XElement Vše
System.Xml.Linq.XName Vše
System.Xml.Linq.XNamespace Vše
System.Xml.Linq.XNode Vše
System.Xml.Linq.XNodeDocumentOrderComparer Vše
System.Xml.Linq.XNodeEqualityComparer Vše
System.Xml.Linq.XObject Vše
System.Xml.Linq.XProcessingInstruction Vše
System.Xml.Linq.XText Vše
System.Xml.XmlNodeType Vše

Kontextová proměnná

Proměnná context je implicitně dostupná ve všech výrazech zásad. Její členové:

  • Zadejte informace relevantní pro požadavek rozhraní API a odpověď a související vlastnosti.
  • Jsou jen pro čtení.
Kontextová proměnná Povolené metody, vlastnosti a hodnoty parametrů
context Api: IApi

Deployment

Uplynulo: TimeSpan – časový interval mezi hodnotou Timestamp a aktuálním časem

GraphQL

LastError

Operation

Request

RequestId: Guid – jedinečný identifikátor požadavku

Response

Subscription

Timestamp: DateTime – bod v čase, kdy byla žádost přijata

Tracing: bool – označuje, jestli je trasování zapnuté nebo vypnuté.

Uživatel

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 (vrátí "spravovanou" pro spravované brány)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (vrátí "spravovanou" pro spravované brány)

InstanceId: string (vrátí "spravovanou" pro spravované brány)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Příklady
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

Další informace o context.LastErrorzpracování chyb naleznete v tématu Zpracování chyb.
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 nebo null pokud požadavek nemá tělo.

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: IPrivateEndpointConnection nebo null pokud požadavek nepochází z připojení privátního koncového bodu.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Vrátí hodnoty hlavičky požadavku oddělené čárkami nebo defaultValue pokud se hlavička nenašla.
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

Vrátí hodnoty hlavičky odpovědi oddělené čárkami nebo defaultValue pokud se hlavička nenajde.
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

- Metody context.Request.Body.As<T>context.Response.Body.As<T> čtou text zprávy požadavku nebo odpovědi v zadaném typu T.

-Nebo-

AsFormUrlEncodedContent(bool preserveContent = false)

- Metody context.Request.Body.AsFormUrlEncodedContent()context.Response.Body.AsFormUrlEncodedContent() čtou data formuláře kódovaná adresou URL v textu zprávy požadavku nebo odpovědi a vrátí IDictionary<string, IList<string> objekt. Dekódovaný objekt podporuje IDictionary operace a následující výrazy: ToQueryString(), , JsonConvert.SerializeObject()ToFormUrlEncodedContent().

Ve výchozím nastavení a As<T>AsFormUrlEncodedContent() metody:
  • Použijte původní základní datový proud zprávy.
  • Vykreslení je nedostupné po vrácení.

Abyste tomu předešli a aby metoda fungovala na kopii základního datového proudu, nastavte preserveContent parametr na true, jak je znázorněno v příkladech zásad set-body .
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

Další informace najdete v rozhraní REST API.
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

Vrátí hodnoty parametrů dotazu oddělené čárkami nebo defaultValue pokud se parametr nenajde.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

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

defaultValue: T

Vrátí přetypování hodnoty proměnné na typ T nebo defaultValue pokud proměnná nebyla nalezena.

Tato metoda vyvolá výjimku, pokud zadaný typ neodpovídá skutečnému typu vrácené proměnné.
BasicAuthCredentials AsBasic(input: this string) input: string

Pokud vstupní parametr obsahuje platnou hodnotu hlavičky požadavku na ověření základního ověřování HTTP, metoda vrátí objekt typu BasicAuthCredentials; jinak metoda vrátí hodnotu null.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Pokud vstupní parametr obsahuje platnou autorizační hodnotu základního ověřování HTTP v hlavičce požadavku, metoda vrátí true a výsledek parametr obsahuje hodnotu typu BasicAuthCredentials; jinak metoda vrátí false.
BasicAuthCredentials Password: string

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

Pokud vstupní parametr obsahuje platnou hodnotu tokenu JWT, vrátí metoda objekt typu Jwt; jinak metoda vrátí null.
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Pokud vstupní parametr obsahuje platnou hodnotu tokenu JWT, metoda vrátí true a výsledek parametr obsahuje hodnotu typu Jwt; jinak metoda vrátí 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

Vrátí hodnoty deklarací identity oddělené čárkami nebo defaultValue pokud se hlavička nenašla.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - prostý text, který se má šifrovat

alg – název symetrického šifrovacího algoritmu

key – šifrovací klíč

iv - inicializační vektor

Vrátí šifrovaný prostý text.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - prostý text, který se má šifrovat

alg – šifrovací algoritmus

Vrátí šifrovaný prostý text.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - prostý text, který se má šifrovat

alg – šifrovací algoritmus

key – šifrovací klíč

iv - inicializační vektor

Vrátí šifrovaný prostý text.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - cypher text, který má být dešifrován

alg – název symetrického šifrovacího algoritmu

key – šifrovací klíč

iv - inicializační vektor

Vrátí prostý text.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - cypher text, který má být dešifrován

alg – šifrovací algoritmus

Vrátí prostý text.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - cypher text, který má být dešifrován

alg – šifrovací algoritmus

key – šifrovací klíč

iv - inicializační vektor

Vrátí prostý text.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) Provede ověření řetězu X.509 bez kontroly stavu odvolání certifikátu.

input – objekt certifikátu

Vrátí true , pokud ověření proběhne úspěšně. false Pokud ověření selže.

Další informace o práci se zásadami najdete tady:

Další informace: