Sdílet prostřednictvím


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

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)

Workspace
context.Api Id: string

IsCurrentRevision: bool

Name: string

Path: string

Revision: string

ServiceUrl: IUrl

Version: string
context.Deployment Gateway

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

Region: string

ServiceId: string

ServiceName: string

SustainabilityInfo

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.Deployment.SustainabilityInfo CurrentCarbonIntensity: Enum CarbonIntentityCategory
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
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
context.Workspace Id: string

Name: string
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
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 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 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 v tématech:

Další informace: