Wyrażenia zasad usługi API Management

DOTYCZY: Wszystkie warstwy usługi API Management

W tym artykule omówiono składnię wyrażeń zasad w języku C# 7. Każde wyrażenie ma dostęp do:

Składnia

  • Wyrażenia pojedynczej instrukcji:
    • Ujęta w element @(expression), gdzie expression jest poprawnie sformułowaną instrukcją wyrażenia języka C#.
  • Wyrażenia z wieloma instrukcjami:
    • Ujęta w @{expression}.
    • Wszystkie ścieżki kodu w wyrażeniach z wieloma instrukcjami muszą kończyć się instrukcją return .

Przykłady

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

}

Użycie

Jeśli nie określono inaczej odwołania do zasad, wyrażenia mogą być używane jako wartości atrybutów lub wartości tekstowe w dowolnych zasadach usługi API Management.

Ważne

Po zdefiniowaniu zasad wyrażenia zasad mają ograniczoną weryfikację. Wyrażenia są wykonywane przez bramę w czasie wykonywania. Wszelkie wyjątki generowane przez wyrażenia zasad powodują błąd środowiska uruchomieniowego.

Typy programu .NET Framework dozwolone w wyrażeniach zasad

W poniższej tabeli wymieniono typy i elementy członkowskie programu .NET Framework dozwolone w wyrażeniach zasad.

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

Zmienna kontekstu

Zmienna context jest niejawnie dostępna w każdym wyrażeniu zasad. Jego członkowie:

  • Podaj informacje istotne dla żądania i odpowiedzi interfejsu API oraz powiązanych właściwości.
  • Wszystkie są tylko do odczytu.
Zmienna kontekstowa Dozwolone metody, właściwości i wartości parametrów
context Api: IApi

Deployment

Upłynął: TimeSpan — przedział czasu między wartością a bieżącą godziną Timestamp

GraphQL

LastError

Operation

Request

RequestId: Guid — unikatowy identyfikator żądania

Response

Subscription

Timestamp: DateTime — punkt w czasie odebrania żądania

Tracing: bool — wskazuje, czy śledzenie jest włączone, czy wyłączone

Użytkownik

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 (zwraca wartość "zarządzaną" dla bram zarządzanych)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (zwraca wartość "zarządzaną" dla bram zarządzanych)

InstanceId: string (zwraca wartość "zarządzaną" dla bram zarządzanych)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Przykłady
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

Aby uzyskać więcej informacji na temat context.LastErrorprogramu , zobacz Obsługa błędów.
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 lub null jeśli żądanie nie ma treści.

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: IPrivateEndpointConnection lub null jeśli żądanie nie pochodzi z prywatnego połączenia punktu końcowego.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Zwraca wartości nagłówka żądania rozdzielanych przecinkami lub defaultValue jeśli nagłówek nie zostanie znaleziony.
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

Zwraca wartości nagłówka odpowiedzi rozdzielanych przecinkami lub defaultValue jeśli nagłówek nie zostanie znaleziony.
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 Do ustalenia

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> i context.Response.Body.As<T> odczytują treść żądania lub komunikatu odpowiedzi w określonym typie T.

-Lub-

AsFormUrlEncodedContent(bool preserveContent = false)

- Metody context.Request.Body.AsFormUrlEncodedContent() i context.Response.Body.AsFormUrlEncodedContent() odczytują dane formularza zakodowane w adresie URL w treści żądania lub komunikatu odpowiedzi i zwracają IDictionary<string, IList<string> obiekt. Obiekt zdekodowany obsługuje IDictionary operacje i następujące wyrażenia: ToQueryString(), , JsonConvert.SerializeObject()ToFormUrlEncodedContent().

Domyślnie metody As<T> i AsFormUrlEncodedContent() :
  • Użyj oryginalnego strumienia treści wiadomości.
  • Renderuj go niedostępny po powrocie.

Aby tego uniknąć, a metoda działa na kopii strumienia treści, ustaw preserveContent parametr na truewartość , jak pokazano w przykładach zasad zestawu treści .
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

Aby uzyskać więcej informacji, zobacz interfejs 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

Zwraca wartości parametrów zapytania rozdzielanych przecinkami lub defaultValue jeśli parametr nie zostanie znaleziony.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

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

defaultValue: T

Zwraca rzutowanie wartości zmiennej na typ T lub defaultValue jeśli zmienna nie zostanie znaleziona.

Ta metoda zgłasza wyjątek, jeśli określony typ nie jest zgodny z rzeczywistym typem zwracanej zmiennej.
BasicAuthCredentials AsBasic(input: this string) input: string

Jeśli parametr wejściowy zawiera prawidłową wartość nagłówka żądania autoryzacji uwierzytelniania podstawowego HTTP, metoda zwraca obiekt typu BasicAuthCredentials; w przeciwnym razie metoda zwraca wartość null.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Jeśli parametr wejściowy zawiera prawidłową wartość autoryzacji uwierzytelniania podstawowego HTTP w nagłówku żądania, metoda zwraca true wartość , a parametr wynikowy zawiera wartość typu BasicAuthCredentials; w przeciwnym razie metoda zwraca falsewartość .
BasicAuthCredentials Password: string

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

Jeśli parametr wejściowy zawiera prawidłową wartość tokenu JWT, metoda zwraca obiekt typu Jwt; w przeciwnym razie metoda zwraca nullwartość .
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Jeśli parametr wejściowy zawiera prawidłową wartość tokenu JWT, metoda zwraca true wartość , a parametr wynikowy zawiera wartość typu Jwt; w przeciwnym razie metoda zwraca falsewartość .
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

Zwraca wartości oświadczeń rozdzielonych przecinkami lub defaultValue jeśli nagłówek nie zostanie znaleziony.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - zwykły tekst do zaszyfrowania

alg - nazwa algorytmu szyfrowania symetrycznego

key - klucz szyfrowania

iv - wektor inicjowania

Zwraca zaszyfrowany zwykły tekst.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - zwykły tekst do zaszyfrowania

alg - algorytm szyfrowania

Zwraca zaszyfrowany zwykły tekst.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - zwykły tekst do zaszyfrowania

alg - algorytm szyfrowania

key - klucz szyfrowania

iv - wektor inicjowania

Zwraca zaszyfrowany zwykły tekst.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - tekst do odszyfrowywania

alg - nazwa algorytmu szyfrowania symetrycznego

key - klucz szyfrowania

iv - wektor inicjowania

Zwraca zwykły tekst.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - tekst do odszyfrowywania

alg - algorytm szyfrowania

Zwraca zwykły tekst.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - tekst do odszyfrowywania

alg - algorytm szyfrowania

key - klucz szyfrowania

iv - wektor inicjowania

Zwraca zwykły tekst.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) Przeprowadza walidację łańcucha X.509 bez sprawdzania stanu odwołania certyfikatu.

input - obiekt certyfikatu

Zwraca wartość true , jeśli walidacja zakończy się powodzeniem; false jeśli walidacja zakończy się niepowodzeniem.

Aby uzyskać więcej informacji na temat pracy z zasadami, zobacz:

Więcej informacji można znaleźć na stronie