Poznámka:
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
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:
- Implicitně poskytnutá kontextová proměnná.
- Povolená podmnožina typů rozhraní .NET Framework.
Syntaxe
-
Výrazy s jedním příkazem:
- Uzavřeno ve
@(expression)výrazu c# ve správném formátu, kdeexpressionje příkaz výrazu jazyka C#.
- Uzavřeno ve
-
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.
- Uzavřeno do
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: IApiDeploymentUplynulo: TimeSpan – časový interval mezi hodnotou Timestamp a aktuálním časemGraphQLLastErrorOperationRequestRequestId: Guid – jedinečný identifikátor požadavkuResponseSubscriptionTimestamp: DateTime – bod v čase, kdy byla žádost přijataTracing: bool – označuje, jestli je trasování zapnuté nebo vypnuté. Uživatel Variables: IReadOnlyDictionary<string, object>void Trace(message: string) Workspace |
context.Api |
Id: stringIsCurrentRevision: boolName: stringPath: stringRevision: stringServiceUrl: IUrlVersion: string |
context.Deployment |
GatewayGatewayId: string (vrátí "spravovanou" pro spravované brány)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: 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: IGraphQLDataObjectParent: IGraphQLDataObjectPříklady |
context.LastError |
Source: stringReason: stringMessage: stringScope: stringSection: stringPath: stringPolicyId: stringDalší informace o context.LastErrorzpracování chyb naleznete v tématu Zpracování chyb. |
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 nebo null pokud požadavek nemá tělo.Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2Headers: IReadOnlyDictionary<string, string[]>IpAddress: stringMatchedParameters: IReadOnlyDictionary<string, string>Method: stringOriginalUrl: IUrlUrl: IUrlPrivateEndpointConnection: 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: stringdefaultValue: stringVrátí hodnoty hlavičky požadavku oddělené čárkami nebo defaultValue pokud se hlavička nenašla. |
context.Response |
Body: IMessageBodyHeaders: IReadOnlyDictionary<string, string[]>StatusCode: intStatusReason: string |
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringVrátí hodnoty hlavičky odpovědi oddělené čárkami nebo defaultValue pokud se hlavička nenajde. |
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 |
TBD |
IGroup |
Id: stringName: 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:
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: stringGroupId: stringMemberName: stringDalší informace najdete v rozhraní REST API. |
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: stringVrátí hodnoty parametrů dotazu oddělené čárkami nebo defaultValue pokud se parametr nenajde. |
IUserIdentity |
Id: stringProvider: string |
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) |
variableName: stringdefaultValue: TVrá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: stringPokud 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: stringresult: out BasicAuthCredentialsPokud 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: stringUserId: string |
Jwt AsJwt(input: this string) |
input: stringPokud 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: stringresult: out JwtPokud 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: 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: stringVrá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á šifrovatalg – název symetrického šifrovacího algoritmukey – šifrovací klíčiv - inicializační vektorVrátí šifrovaný prostý text. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - prostý text, který se má šifrovatalg – šifrovací algoritmusVrátí šifrovaný prostý text. |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - prostý text, který se má šifrovatalg – šifrovací algoritmuskey – šifrovací klíčiv - inicializační vektorVrátí šifrovaný prostý text. |
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - cypher text, který má být dešifrovánalg – název symetrického šifrovacího algoritmukey – šifrovací klíčiv - inicializační vektorVrátí prostý text. |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - cypher text, který má být dešifrovánalg – šifrovací algoritmusVrá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ánalg – šifrovací algoritmuskey – šifrovací klíčiv - inicializační vektorVrá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átuVrátí true , pokud ověření proběhne úspěšně. false Pokud ověření selže. |
Související obsah
Další informace o práci se zásadami najdete v tématech:
- Kurz: Transformace a ochrana rozhraní API
- Referenční informace o zásadách pro úplný seznam prohlášení o zásadách a jejich nastavení
- Výrazy zásad
- Nastavení nebo úprava zásad
- Znovu použít konfigurace zásad
- Úložiště fragmentů zásad
- Úložiště dětského hřiště zásad
- Sada nástrojů zásad služby Azure API Management
- Získejte asistenci Copilotu při vytváření, vysvětlování a řešení problémů se zásadami.
Další informace:
- Podívejte se, jak do back-endové služby zadat kontextové informace. K zadání těchto informací použijte parametr Set řetězec dotazu a nastavte zásady hlavičky HTTP.
- Podívejte se, jak použít zásadu Validate JWT k předběžné autorizaci přístupu k operacím na základě deklarací identity tokenů.
- Zjistěte, jak pomocí trasování rozhraní API zjistit, jak se zásady vyhodnocují, a výsledky těchto vyhodnocení.
- Zjistěte, jak pomocí výrazů získat z mezipaměti a úložiště zásady mezipaměti nakonfigurovat ukládání odpovědí služby API Management do mezipaměti. Nastavte dobu trvání, která odpovídá ukládání odpovědí do mezipaměti back-endové služby podle direktivy
Cache-Controlzálohované služby. - Podívejte se, jak provádět filtrování obsahu. Pomocí toku řízení a nastavení zásad těla odeberte datové prvky z odpovědi přijaté z back-endu.
- Pokud si chcete stáhnout prohlášení o zásadách, přečtěte si úložiště api-management-samples/policies na GitHubu.