Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of mappen te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen om mappen te wijzigen.
VAN TOEPASSING OP: Alle API Management-lagen
In dit artikel worden de syntaxis van beleidsexpressies in C# 7 besproken. Elke expressie heeft toegang tot:
- De impliciet opgegeven contextvariabele .
- Een toegestane subset van .NET Framework-typen.
Syntaxis
-
Expressies met één instructie:
- Ingesloten in
@(expression), waarexpressioneen goed gevormde C#-expressie-instructie is.
- Ingesloten in
-
Expressies met meerdere instructies:
- Ingesloten in
@{expression}. - Alle codepaden binnen expressies met meerdere instructies moeten eindigen met een
returninstructie.
- Ingesloten in
Voorbeelden
@(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;
}
Gebruik
Tenzij de beleidsreferentie anders aangeeft, kunnen expressies worden gebruikt als kenmerkwaarden of tekstwaarden in een API Management-beleid.
Belangrijk
Wanneer het beleid is gedefinieerd, hebben beleidsexpressies slechts beperkte verificatie. Expressies worden tijdens runtime uitgevoerd door de gateway. Uitzonderingen die worden gegenereerd door beleidsexpressies, resulteren in een runtimefout.
.NET Framework-typen die zijn toegestaan in beleidsexpressies
De volgende tabel bevat de .NET Framework-typen en leden die zijn toegestaan in beleidsexpressies.
| Typologie | Ondersteunde leden |
|---|---|
Newtonsoft.Json.Formatting |
Alle |
Newtonsoft.Json.JsonConvert |
SerializeObject, DeserializeObject |
Newtonsoft.Json.Linq.Extensions |
Alle |
Newtonsoft.Json.Linq.JArray |
Alle |
Newtonsoft.Json.Linq.JConstructor |
Alle |
Newtonsoft.Json.Linq.JContainer |
Alle |
Newtonsoft.Json.Linq.JObject |
Alle |
Newtonsoft.Json.Linq.JProperty |
Alle |
Newtonsoft.Json.Linq.JRaw |
Alle |
Newtonsoft.Json.Linq.JToken |
Alle |
Newtonsoft.Json.Linq.JTokenType |
Alle |
Newtonsoft.Json.Linq.JValue |
Alle |
System.Array |
Alle |
System.BitConverter |
Alle |
System.Boolean |
Alle |
System.Byte |
Alle |
System.Char |
Alle |
System.Collections.Generic.Dictionary<TKey, TValue> |
Alle |
System.Collections.Generic.HashSet<T> |
Alle |
System.Collections.Generic.ICollection<T> |
Alle |
System.Collections.Generic.IDictionary<TKey, TValue> |
Alle |
System.Collections.Generic.IEnumerable<T> |
Alle |
System.Collections.Generic.IEnumerator<T> |
Alle |
System.Collections.Generic.IList<T> |
Alle |
System.Collections.Generic.IReadOnlyCollection<T> |
Alle |
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> |
Alle |
System.Collections.Generic.ISet<T> |
Alle |
System.Collections.Generic.KeyValuePair<TKey, TValue> |
Alle |
System.Collections.Generic.List<T> |
Alle |
System.Collections.Generic.Queue<T> |
Alle |
System.Collections.Generic.Stack<T> |
Alle |
System.Convert |
Alle |
System.DateTime |
(Constructor), Add, , AddDaysAddHours, AddMilliseconds, , AddMinutes, AddMonths, AddSeconds, , , AddTicksAddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonthNowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear |
System.DateTimeKind |
Utc |
System.DateTimeOffset |
Alle |
System.Decimal |
Alle |
System.Double |
Alle |
System.Enum |
Parse, , TryParseToString |
System.Exception |
Alle |
System.Guid |
Alle |
System.Int16 |
Alle |
System.Int32 |
Alle |
System.Int64 |
Alle |
System.IO.StringReader |
Alle |
System.IO.StringWriter |
Alle |
System.Linq.Enumerable |
Alle |
System.Math |
Alle |
System.MidpointRounding |
Alle |
System.Net.IPAddress |
AddressFamily, , EqualsGetAddressBytes, IsLoopback, , Parse, , TryParseToString |
System.Net.WebUtility |
Alle |
System.Nullable |
Alle |
System.Random |
Alle |
System.SByte |
Alle |
System.Security.Cryptography.AsymmetricAlgorithm |
Alle |
System.Security.Cryptography.CipherMode |
Alle |
System.Security.Cryptography.HashAlgorithm |
Alle |
System.Security.Cryptography.HashAlgorithmName |
Alle |
System.Security.Cryptography.HMAC |
Alle |
System.Security.Cryptography.HMACMD5 |
Alle |
System.Security.Cryptography.HMACSHA1 |
Alle |
System.Security.Cryptography.HMACSHA256 |
Alle |
System.Security.Cryptography.HMACSHA384 |
Alle |
System.Security.Cryptography.HMACSHA512 |
Alle |
System.Security.Cryptography.KeyedHashAlgorithm |
Alle |
System.Security.Cryptography.MD5 |
Alle |
System.Security.Cryptography.Oid |
Alle |
System.Security.Cryptography.PaddingMode |
Alle |
System.Security.Cryptography.RNGCryptoServiceProvider |
Alle |
System.Security.Cryptography.RSA |
Alle |
System.Security.Cryptography.RSAEncryptionPadding |
Alle |
System.Security.Cryptography.RSASignaturePadding |
Alle |
System.Security.Cryptography.SHA1 |
Alle |
System.Security.Cryptography.SHA1Managed |
Alle |
System.Security.Cryptography.SHA256 |
Alle |
System.Security.Cryptography.SHA256Managed |
Alle |
System.Security.Cryptography.SHA384 |
Alle |
System.Security.Cryptography.SHA384Managed |
Alle |
System.Security.Cryptography.SHA512 |
Alle |
System.Security.Cryptography.SHA512Managed |
Alle |
System.Security.Cryptography.SymmetricAlgorithm |
Alle |
System.Security.Cryptography.X509Certificates.PublicKey |
Alle |
System.Security.Cryptography.X509Certificates.RSACertificateExtensions |
Alle |
System.Security.Cryptography.X509Certificates.X500DistinguishedName |
Name |
System.Security.Cryptography.X509Certificates.X509Certificate |
Alle |
System.Security.Cryptography.X509Certificates.X509Certificate2 |
Alle |
System.Security.Cryptography.X509Certificates.X509ContentType |
Alle |
System.Security.Cryptography.X509Certificates.X509NameType |
Alle |
System.Single |
Alle |
System.String |
Alle |
System.StringComparer |
Alle |
System.StringComparison |
Alle |
System.StringSplitOptions |
Alle |
System.Text.Encoding |
Alle |
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 |
(Constructor), IsMatch, Match, Matches, , Replace, UnescapeSplit |
System.Text.RegularExpressions.RegexOptions |
Alle |
System.Text.StringBuilder |
Alle |
System.TimeSpan |
Alle |
System.TimeZone |
Alle |
System.TimeZoneInfo.AdjustmentRule |
Alle |
System.TimeZoneInfo.TransitionTime |
Alle |
System.TimeZoneInfo |
Alle |
System.Tuple |
Alle |
System.UInt16 |
Alle |
System.UInt32 |
Alle |
System.UInt64 |
Alle |
System.Uri |
Alle |
System.UriPartial |
Alle |
System.Xml.Linq.Extensions |
Alle |
System.Xml.Linq.XAttribute |
Alle |
System.Xml.Linq.XCData |
Alle |
System.Xml.Linq.XComment |
Alle |
System.Xml.Linq.XContainer |
Alle |
System.Xml.Linq.XDeclaration |
Alle |
System.Xml.Linq.XDocument |
Alles, behalve Load |
System.Xml.Linq.XDocumentType |
Alle |
System.Xml.Linq.XElement |
Alle |
System.Xml.Linq.XName |
Alle |
System.Xml.Linq.XNamespace |
Alle |
System.Xml.Linq.XNode |
Alle |
System.Xml.Linq.XNodeDocumentOrderComparer |
Alle |
System.Xml.Linq.XNodeEqualityComparer |
Alle |
System.Xml.Linq.XObject |
Alle |
System.Xml.Linq.XProcessingInstruction |
Alle |
System.Xml.Linq.XText |
Alle |
System.Xml.XmlNodeType |
Alle |
Contextvariabele
De context variabele is impliciet beschikbaar in elke beleidsexpressie. De leden:
- Geef informatie op die relevant is voor de API-aanvraag en -reactie en gerelateerde eigenschappen.
- Zijn allemaal alleen-lezen.
| Contextvariabele | Toegestane methoden, eigenschappen en parameterwaarden |
|---|---|
context |
Api: IApiDeploymentVerstreken: TimeSpan - tijdsinterval tussen de waarde van Timestamp en de huidige tijdGraphQLLastErrorOperationRequestRequestId: Guid - unieke aanvraag-idResponseSubscriptionTimestamp: DateTime - tijdstip waarop de aanvraag is ontvangenTracing: bool - geeft aan of tracering is ingeschakeld of uitgeschakeld Gebruiker Variables: IReadOnlyDictionary<string, object>void Trace(message: string) Workspace |
context.Api |
Id: stringIsCurrentRevision: boolName: stringPath: stringRevision: stringServiceUrl: IUrlVersion: string |
context.Deployment |
GatewayGatewayId: string (retourneert 'beheerd' voor beheerde gateways)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id: string (retourneert 'beheerd' voor beheerde gateways)InstanceId: string (retourneert 'beheerd' voor beheerde gateways)IsManaged: bool |
context.Deployment.SustainabilityInfo |
CurrentCarbonIntensity: Enum CarbonIntensityCategory |
context.GraphQL |
GraphQLArguments: IGraphQLDataObjectParent: IGraphQLDataObjectVoorbeelden |
context.LastError |
Source: stringReason: stringMessage: stringScope: stringSection: stringPath: stringPolicyId: stringZie Foutafhandeling voor meer informatie over. context.LastError |
context.Operation |
Id: stringMethod: stringName: stringUrlTemplate: string |
context.Product |
ApprovalRequired: boolGroups: IEnumerable<IGroup>Id: stringName: stringState: enum ProductState {NotPublished, Published}SubscriptionsLimit: int?SubscriptionRequired: bool |
context.Request |
Body: IMessageBody of null als de aanvraag geen hoofdtekst heeft.Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2Headers: IReadOnlyDictionary<string, string[]>IpAddress: stringMatchedParameters: IReadOnlyDictionary<string, string>Method: stringOriginalUrl: IUrlUrl: IUrlPrivateEndpointConnection: IPrivateEndpointConnection of null als de aanvraag niet afkomstig is van een privé-eindpuntverbinding. |
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringRetourneert waarden voor door komma's gescheiden aanvraagheaders of defaultValue als de header niet wordt gevonden. |
context.Response |
Body: IMessageBodyHeaders: IReadOnlyDictionary<string, string[]>StatusCode: intStatusReason: string |
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringRetourneert door komma's gescheiden antwoordheaderwaarden of defaultValue als de header niet wordt gevonden. |
context.Subscription |
CreatedDate: DateTimeEndDate: DateTime?Id: stringKey: stringName: stringPrimaryKey: stringSecondaryKey: stringStartDate: DateTime? |
context.User |
Email: stringFirstName: stringGroups: IEnumerable<IGroup>Id: stringIdentities: IEnumerable<IUserIdentity>LastName: stringNote: stringRegistrationDate: DateTime |
context.Workspace |
Id: stringName: string |
IApi |
Id: stringName: stringPath: stringProtocols: IEnumerable<string>ServiceUrl: IUrlSubscriptionKeyParameterNames: ISubscriptionKeyParameterNames |
IGraphQLDataObject |
N.t.b. |
IGroup |
Id: stringName: string |
IMessageBody |
As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument - De context.Request.Body.As<T> en context.Response.Body.As<T> methoden lezen een berichttekst van een aanvraag of antwoord in het opgegeven type T. -Of- AsFormUrlEncodedContent(bool preserveContent = false) - De context.Request.Body.AsFormUrlEncodedContent() en context.Response.Body.AsFormUrlEncodedContent() methoden lezen met URL-gecodeerde formuliergegevens in een hoofdtekst van een aanvraag- of antwoordbericht en retourneren een IDictionary<string, IList<string> object. Het gedecodeerde object ondersteunt IDictionary bewerkingen en de volgende expressies: ToQueryString(), , JsonConvert.SerializeObject()ToFormUrlEncodedContent(). Standaard worden de As<T> en AsFormUrlEncodedContent() methoden gebruikt:
Om dat te voorkomen en de methode te laten werken op een kopie van de hoofdtekststroom, stelt u de preserveContent parameter truein op , zoals wordt weergegeven in voorbeelden voor het beleid voor de set-body . |
IPrivateEndpointConnection |
Name: stringGroupId: stringMemberName: stringZie de REST API voor meer informatie. |
IUrl |
Host: stringPath: stringPort: intQuery: IReadOnlyDictionary<string, string[]>QueryString: stringScheme: string |
ISubscriptionKeyParameterNames |
Header: stringQuery: string |
string IUrl.Query.GetValueOrDefault(queryParameterName: string, defaultValue: string) |
queryParameterName: stringdefaultValue: stringRetourneert door komma's gescheiden queryparameterwaarden of defaultValue als de parameter niet wordt gevonden. |
IUserIdentity |
Id: stringProvider: string |
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) |
variableName: stringdefaultValue: TRetourneert een variabelewaarde die moet worden getypt T of defaultValue als de variabele niet wordt gevonden.Met deze methode wordt een uitzondering gegenereerd als het opgegeven type niet overeenkomt met het werkelijke type van de geretourneerde variabele. |
BasicAuthCredentials AsBasic(input: this string) |
input: stringAls de invoerparameter een geldige headerwaarde voor de aanvraag voor http-basisverificatie bevat, retourneert de methode een object van het type BasicAuthCredentials; anders retourneert de methode null. |
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) |
input: stringresult: out BasicAuthCredentialsAls de invoerparameter een geldige autorisatiewaarde voor HTTP Basic Authentication in de aanvraagheader bevat, retourneert true de methode en bevat de resultaatparameter een waarde van het type BasicAuthCredentials; anders retourneert falsede methode. |
BasicAuthCredentials |
Password: stringUserId: string |
Jwt AsJwt(input: this string) |
input: stringAls de invoerparameter een geldige JWT-waarde bevat, retourneert de methode een object van het type Jwt; anders retourneert nullde methode . |
bool TryParseJwt(input: this string, result: out Jwt) |
input: stringresult: out JwtAls de invoerparameter een geldige JWT-waarde bevat, retourneert true de methode en bevat de resultaatparameter een waarde van het type Jwt; anders retourneert falsede methode. |
Jwt |
Algorithm: stringAudiences: IEnumerable<string>Claims: IReadOnlyDictionary<string, string[]>ExpirationTime: DateTime?Id: stringIssuer: stringIssuedAt: DateTime?NotBefore: DateTime?Subject: stringType: string |
string Jwt.Claims.GetValueOrDefault(claimName: string, defaultValue: string) |
claimName: stringdefaultValue: stringRetourneert door komma's gescheiden claimwaarden of defaultValue als de header niet wordt gevonden. |
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - tekst zonder opmaak die moet worden versleuteldalg - naam van een symmetrisch versleutelingsalgoritmenkey -Coderingssleuteliv - initialisatievectorRetourneert versleutelde tekst zonder opmaak. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - tekst zonder opmaak die moet worden versleuteldalg -CoderingsalgoritmeRetourneert versleutelde tekst zonder opmaak. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - tekst zonder opmaak die moet worden versleuteldalg -Coderingsalgoritmekey -Coderingssleuteliv - initialisatievectorRetourneert versleutelde tekst zonder opmaak. |
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - versleutelingstekst die moet worden ontsleuteldalg - naam van een symmetrisch versleutelingsalgoritmenkey -Coderingssleuteliv - initialisatievectorRetourneert tekst zonder opmaak. |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - versleutelingstekst die moet worden ontsleuteldalg -CoderingsalgoritmeRetourneert tekst zonder opmaak. |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - versleutelingstekst die moet worden ontsleuteldalg -Coderingsalgoritmekey -Coderingssleuteliv - initialisatievectorRetourneert tekst zonder opmaak. |
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) |
Voert een X.509-ketenvalidatie uit zonder de certificaatintrekkingsstatus te controleren.input - certificaatobjectRetourneert true als de validatie slaagt. false Als de validatie mislukt. |
Gerelateerde inhoud
Zie voor meer informatie over het werken met beleid:
- Zelfstudie: Uw API transformeren en beveiligen
- Beleidsreferentie voor een volledige lijst met beleidsinstructies en hun instellingen
- Beleidsexpressies
- Beleid definiëren of bijwerken
- Beleidsconfiguraties opnieuw gebruiken
- Beleidsfragmentenopslagplaats
- Beleidsspeelplaats
- Azure API Management-beleidstoolkit
- Krijg hulp van Copilot bij het maken, uitleggen en oplossen van problemen met beleid.
Bekijk voor meer informatie:
- Zie hoe u contextinformatie kunt opgeven voor uw back-endservice. Gebruik de queryreeksparameter instellen en STEL HTTP-headerbeleid in om deze informatie op te geven.
- Lees hoe u het JWT-beleid valideren gebruikt om de toegang tot bewerkingen vooraf te autoriseren op basis van tokenclaims.
- Lees hoe u API-tracering gebruikt om te detecteren hoe beleidsregels worden geëvalueerd en de resultaten van deze evaluaties.
- Zie hoe u expressies gebruikt met de get from cache en Store om beleid voor API Management-reacties te configureren. Stel een duur in die overeenkomt met de reactiecache van de back-endservice, zoals is opgegeven door de instructie van
Cache-Controlde ondersteunde service. - Zie hoe u inhoudsfilters uitvoert. Verwijder gegevenselementen uit het antwoord dat is ontvangen van de back-end met behulp van de besturingsstroom en stel hoofdtekstbeleidsregels in.
- Zie de GitHub-opslagplaats api-management-samples/policies om de beleidsinstructies te downloaden.