API Management-szabályzatkifejezések

A KÖVETKEZŐRE VONATKOZIK: Minden API Management-szint

Ez a cikk a szabályzatkifejezések szintaxisát ismerteti a C# 7-ben. Minden kifejezés rendelkezik hozzáféréssel a következőhöz:

Syntax

  • Egyutas kifejezések:
    • Zárt, @(expression)ahol expression egy jól formázott C# kifejezési utasítás.
  • Többutas kifejezések:
    • Be van zárva a @{expression}.
    • A többutas kifejezések összes kódútvonalának utasítással return kell végződnie.

Példák

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

}

Használat

Ha a szabályzathivatkozás másként nem rendelkezik, a kifejezések attribútumértékekként vagy szöveges értékekként használhatók bármely API Management-házirendben.

Fontos

A szabályzat definiálásakor a szabályzatkifejezések csak korlátozott ellenőrzéssel rendelkeznek. A kifejezéseket az átjáró futásidőben hajtja végre. A szabályzatkifejezések által létrehozott kivételek futásidejű hibát eredményeznek.

.NET-keretrendszer szabályzatkifejezésekben engedélyezett típusok

Az alábbi táblázat a szabályzatkifejezésekben engedélyezett .NET-keretrendszer típusokat és tagokat sorolja fel.

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

Környezeti változó

A context változó implicit módon elérhető minden szabályzatkifejezésben. Tagjai:

  • Adja meg az API-kéréssel és -válaszsal kapcsolatos információkat, valamint a kapcsolódó tulajdonságokat.
  • Az összes írásvédett.
Környezeti változó Engedélyezett metódusok, tulajdonságok és paraméterértékek
context Api: IApi

Deployment

Eltelt: TimeSpan - az érték Timestamp és az aktuális idő közötti időintervallum

GraphQL

LastError

Operation

Request

RequestId: Guid - egyedi kérésazonosító

Response

Subscription

Timestamp: DateTime – a kérelem beérkezésének időpontja

Tracing: bool - azt jelzi, hogy a nyomkövetés be- vagy ki van-e kapcsolva

Felhasználó

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 (felügyelt átjárók esetén "felügyelt" értéket ad vissza)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (felügyelt átjárók esetén "felügyelt" értéket ad vissza)

InstanceId: string (felügyelt átjárók esetén "felügyelt" értéket ad vissza)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Példák
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

További információ: context.LastErrorHibakezelés.
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 vagy null ha a kérelemnek nincs törzse.

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: IPrivateEndpointConnection vagy null ha a kérés nem privát végpontkapcsolatból származik.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Vesszővel elválasztott kérelemfejlécértékeket ad vissza, vagy defaultValue ha a fejléc nem található.
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

Vesszővel elválasztott válaszfejlécértékeket ad vissza, vagy defaultValue ha a fejléc nem található.
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 Később eldöntendő

IGroup Id: string

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

- A context.Request.Body.As<T> metódusok egy context.Response.Body.As<T> kérés vagy válaszüzenet törzsét olvassák be a megadott típusban T.

-Vagy-

AsFormUrlEncodedContent(bool preserveContent = false)

– Az context.Request.Body.AsFormUrlEncodedContent() URL-címmel kódolt űrlapadatok beolvasása a kérelem- vagy válaszüzenetek törzsében és context.Response.Body.AsFormUrlEncodedContent() egy objektum visszaadása IDictionary<string, IList<string> . A dekódolt objektum támogatja IDictionary a műveleteket és a következő kifejezéseket: ToQueryString(), , JsonConvert.SerializeObject(), ToFormUrlEncodedContent().

Alapértelmezés szerint a As<T> következő módszerek és AsFormUrlEncodedContent() módszerek:
  • Használja az eredeti üzenettörzs-adatfolyamot.
  • A visszatérés után nem érhető el.

Annak érdekében, hogy ez elkerülhető legyen, és a metódus a törzsfolyam egy példányán működjön, állítsa a preserveContent paramétert truea beállítástörzs-szabályzat példáiban látható módon.
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

További információkért lásd a REST API-t.
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

Vesszővel elválasztott lekérdezési paraméterértékeket ad vissza, vagy defaultValue ha a paraméter nem található.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

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

defaultValue: T

A változó értékének beírását T adja vissza, vagy defaultValue ha a változó nem található.

Ez a metódus kivételt eredményez, ha a megadott típus nem egyezik a visszaadott változó tényleges típusával.
BasicAuthCredentials AsBasic(input: this string) input: string

Ha a bemeneti paraméter érvényes HTTP Basic Authentication engedélyezési kérelem fejlécértéket tartalmaz, a metódus egy típusú BasicAuthCredentialsobjektumot ad vissza, ellenkező esetben a metódus null értéket ad vissza.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Ha a bemeneti paraméter érvényes HTTP Basic Authentication-hitelesítési értéket tartalmaz a kérelem fejlécében, a metódus visszaadja true a metódust, és az eredményparaméter típusértéket BasicAuthCredentialstartalmaz, ellenkező esetben a metódus ad vissza false.
BasicAuthCredentials Password: string

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

Ha a bemeneti paraméter érvényes JWT-tokenértéket tartalmaz, a metódus egy típusú Jwtobjektumot ad vissza, ellenkező esetben a metódus visszaadja null.
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Ha a bemeneti paraméter érvényes JWT-jogkivonat-értéket tartalmaz, a metódus visszaadja true , és az eredményparaméter típusértéket Jwttartalmaz, ellenkező esetben a metódus visszaadja 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

Vesszővel elválasztott jogcímértékeket ad vissza, vagy defaultValue ha a fejléc nem található.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - titkosítandó egyszerű szöveg

alg - szimmetrikus titkosítási algoritmus neve

key - titkosítási kulcs

iv - inicializálási vektor

Titkosított egyszerű szöveget ad vissza.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - titkosítandó egyszerű szöveg

alg - titkosítási algoritmus

Titkosított egyszerű szöveget ad vissza.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - titkosítandó egyszerű szöveg

alg - titkosítási algoritmus

key - titkosítási kulcs

iv - inicializálási vektor

Titkosított egyszerű szöveget ad vissza.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input - visszafejtendő kódolt szöveg

alg - szimmetrikus titkosítási algoritmus neve

key - titkosítási kulcs

iv - inicializálási vektor

Egyszerű szöveget ad vissza.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input - visszafejtendő kódolt szöveg

alg - titkosítási algoritmus

Egyszerű szöveget ad vissza.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input - visszafejtendő kódolt szöveg

alg - titkosítási algoritmus

key - titkosítási kulcs

iv - inicializálási vektor

Egyszerű szöveget ad vissza.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) X.509-láncérvényesítést hajt végre a tanúsítvány visszavonási állapotának ellenőrzése nélkül.

input - tanúsítványobjektum

Visszaadja true , ha az érvényesítés sikeres; false ha az érvényesítés sikertelen.

A szabályzatokkal kapcsolatos további információkért lásd:

További információk:

  • Megtudhatja, hogyan adhatja meg a háttérszolgáltatás környezeti adatait. Az információk megadásához használja a Lekérdezési sztring beállítása paramétert és a HTTP-fejlécszabályzatok beállítását.
  • Megtudhatja, hogyan használhatja a JWT-szabályzatot a műveletekhez való hozzáférés jogkivonatok alapján történő előzetes engedélyezéséhez.
  • Megtudhatja, hogyan használhat api Inspector-nyomkövetést a szabályzatok kiértékelésének és az értékelések eredményeinek észleléséhez.
  • Megtudhatja, hogyan használhat kifejezéseket a Get from cache és a Store használatával gyorsítótárazási szabályzatokkal az API Management válasz gyorsítótárazásának konfigurálásához. Állítson be egy időtartamot, amely megfelel a háttérszolgáltatás válasz gyorsítótárazásának a háttérszolgáltatás irányelvében Cache-Control meghatározottak szerint.
  • Megtudhatja, hogyan végezhet tartalomszűrést. Távolítsa el az adatelemeket a háttérrendszertől kapott válaszból a Control flow és a Set body policies használatával.
  • A szabályzatutasítók letöltéséhez tekintse meg az api-management-samples/policies GitHub adattárat.