適用対象: すべての API Management レベル
この記事では、C# 7 のポリシー式の構文について説明します。 各式には、次のアクセス権があります。
構文
-
単一ステートメント式:
- 単一ステートメント式は
@(expression)で囲みます。expressionは正しい形式の C# 式ステートメントです。
- 単一ステートメント式は
-
複数ステートメント式:
-
@{expression}で囲みます。 - 複数ステートメントの式内のすべてのコード パスは
returnステートメントで終了している必要があります。
-
例
@(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;
}
使用法
ポリシー参照で特に指定されていない限り、式は任意の API Management ポリシーで属性値またはテキスト値として使用できます。
重要
ポリシーが定義されている場合、ポリシー式の検証は制限されます。 式は、実行時にゲートウェイによって実行されます。 ポリシー式によって生成された例外は、ランタイム エラーになります。
ポリシー式で使用できる .NET Framework の型
次の表は、ポリシー式で使用できる .NET Framework の型とメンバーの一覧です。
| タイプ | サポートされているメンバー |
|---|---|
Newtonsoft.Json.Formatting |
すべて |
Newtonsoft.Json.JsonConvert |
SerializeObject、DeserializeObject |
Newtonsoft.Json.Linq.Extensions |
すべて |
Newtonsoft.Json.Linq.JArray |
すべて |
Newtonsoft.Json.Linq.JConstructor |
すべて |
Newtonsoft.Json.Linq.JContainer |
すべて |
Newtonsoft.Json.Linq.JObject |
すべて |
Newtonsoft.Json.Linq.JProperty |
すべて |
Newtonsoft.Json.Linq.JRaw |
すべて |
Newtonsoft.Json.Linq.JToken |
すべて |
Newtonsoft.Json.Linq.JTokenType |
すべて |
Newtonsoft.Json.Linq.JValue |
すべて |
System.Array |
すべて |
System.BitConverter |
すべて |
System.Boolean |
すべて |
System.Byte |
すべて |
System.Char |
すべて |
System.Collections.Generic.Dictionary<TKey, TValue> |
すべて |
System.Collections.Generic.HashSet<T> |
すべて |
System.Collections.Generic.ICollection<T> |
すべて |
System.Collections.Generic.IDictionary<TKey, TValue> |
すべて |
System.Collections.Generic.IEnumerable<T> |
すべて |
System.Collections.Generic.IEnumerator<T> |
すべて |
System.Collections.Generic.IList<T> |
すべて |
System.Collections.Generic.IReadOnlyCollection<T> |
すべて |
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> |
すべて |
System.Collections.Generic.ISet<T> |
すべて |
System.Collections.Generic.KeyValuePair<TKey, TValue> |
すべて |
System.Collections.Generic.List<T> |
すべて |
System.Collections.Generic.Queue<T> |
すべて |
System.Collections.Generic.Stack<T> |
すべて |
System.Convert |
すべて |
System.DateTime |
(Constructor)、Add、AddDays、AddHours、AddMilliseconds、AddMinutes、AddMonths、AddSeconds、AddTicks、AddYears、Date、Day、DayOfWeek、DayOfYear、DaysInMonth、Hour、IsDaylightSavingTime、IsLeapYear、MaxValue、Millisecond、Minute、MinValue、Month、Now、Parse、Second、Subtract、Ticks、TimeOfDay、Today、ToString、UtcNow、Year |
System.DateTimeKind |
Utc |
System.DateTimeOffset |
すべて |
System.Decimal |
すべて |
System.Double |
すべて |
System.Enum |
Parse、TryParse、ToString |
System.Exception |
すべて |
System.Guid |
すべて |
System.Int16 |
すべて |
System.Int32 |
すべて |
System.Int64 |
すべて |
System.IO.StringReader |
すべて |
System.IO.StringWriter |
すべて |
System.Linq.Enumerable |
すべて |
System.Math |
すべて |
System.MidpointRounding |
すべて |
System.Net.IPAddress |
AddressFamily、Equals、GetAddressBytes、IsLoopback、Parse、TryParse、ToString |
System.Net.WebUtility |
すべて |
System.Nullable |
すべて |
System.Random |
すべて |
System.SByte |
すべて |
System.Security.Cryptography.AsymmetricAlgorithm |
すべて |
System.Security.Cryptography.CipherMode |
すべて |
System.Security.Cryptography.HashAlgorithm |
すべて |
System.Security.Cryptography.HashAlgorithmName |
すべて |
System.Security.Cryptography.HMAC |
すべて |
System.Security.Cryptography.HMACMD5 |
すべて |
System.Security.Cryptography.HMACSHA1 |
すべて |
System.Security.Cryptography.HMACSHA256 |
すべて |
System.Security.Cryptography.HMACSHA384 |
すべて |
System.Security.Cryptography.HMACSHA512 |
すべて |
System.Security.Cryptography.KeyedHashAlgorithm |
すべて |
System.Security.Cryptography.MD5 |
すべて |
System.Security.Cryptography.Oid |
すべて |
System.Security.Cryptography.PaddingMode |
すべて |
System.Security.Cryptography.RNGCryptoServiceProvider |
すべて |
System.Security.Cryptography.RSA |
すべて |
System.Security.Cryptography.RSAEncryptionPadding |
すべて |
System.Security.Cryptography.RSASignaturePadding |
すべて |
System.Security.Cryptography.SHA1 |
すべて |
System.Security.Cryptography.SHA1Managed |
すべて |
System.Security.Cryptography.SHA256 |
すべて |
System.Security.Cryptography.SHA256Managed |
すべて |
System.Security.Cryptography.SHA384 |
すべて |
System.Security.Cryptography.SHA384Managed |
すべて |
System.Security.Cryptography.SHA512 |
すべて |
System.Security.Cryptography.SHA512Managed |
すべて |
System.Security.Cryptography.SymmetricAlgorithm |
パラメータレスを除いてすべて Create() |
System.Security.Cryptography.X509Certificates.PublicKey |
すべて |
System.Security.Cryptography.X509Certificates.RSACertificateExtensions |
すべて |
System.Security.Cryptography.X509Certificates.X500DistinguishedName |
Name |
System.Security.Cryptography.X509Certificates.X509Certificate |
すべて |
System.Security.Cryptography.X509Certificates.X509Certificate2 |
すべて |
System.Security.Cryptography.X509Certificates.X509ContentType |
すべて |
System.Security.Cryptography.X509Certificates.X509NameType |
すべて |
System.Single |
すべて |
System.String |
すべて |
System.StringComparer |
すべて |
System.StringComparison |
すべて |
System.StringSplitOptions |
すべて |
System.Text.Encoding |
すべて |
System.Text.RegularExpressions.Capture |
Index、Length、Value |
System.Text.RegularExpressions.CaptureCollection |
Count、Item |
System.Text.RegularExpressions.Group |
Captures、Success |
System.Text.RegularExpressions.GroupCollection |
Count、Item |
System.Text.RegularExpressions.Match |
Empty、Groups、Result |
System.Text.RegularExpressions.Regex |
(Constructor)、IsMatch、Match、Matches、Replace、Unescape、Split |
System.Text.RegularExpressions.RegexOptions |
すべて |
System.Text.StringBuilder |
すべて |
System.TimeSpan |
すべて |
System.TimeZone |
すべて |
System.TimeZoneInfo.AdjustmentRule |
すべて |
System.TimeZoneInfo.TransitionTime |
すべて |
System.TimeZoneInfo |
すべて |
System.Tuple |
すべて |
System.UInt16 |
すべて |
System.UInt32 |
すべて |
System.UInt64 |
すべて |
System.Uri |
すべて |
System.UriPartial |
すべて |
System.Xml.Linq.Extensions |
すべて |
System.Xml.Linq.XAttribute |
すべて |
System.Xml.Linq.XCData |
すべて |
System.Xml.Linq.XComment |
すべて |
System.Xml.Linq.XContainer |
すべて |
System.Xml.Linq.XDeclaration |
すべて |
System.Xml.Linq.XDocument |
Load を除くすべて |
System.Xml.Linq.XDocumentType |
すべて |
System.Xml.Linq.XElement |
すべて |
System.Xml.Linq.XName |
すべて |
System.Xml.Linq.XNamespace |
すべて |
System.Xml.Linq.XNode |
すべて |
System.Xml.Linq.XNodeDocumentOrderComparer |
すべて |
System.Xml.Linq.XNodeEqualityComparer |
すべて |
System.Xml.Linq.XObject |
すべて |
System.Xml.Linq.XProcessingInstruction |
すべて |
System.Xml.Linq.XText |
すべて |
System.Xml.XmlNodeType |
すべて |
コンテキストの変数
context 変数は、暗黙的にすべてのポリシー式で使用できます。 そのメンバーは次のようになります。
| コンテキスト変数 | 使用可能なメソッド、プロパティ、パラメーターの値 |
|---|---|
context |
Api: IApiDeployment経過時間: TimeSpan - Timestampの値と現在の時刻の間の時間間隔GraphQLLastErrorOperationRequestRequestId: Guid - 一意の要求識別子ResponseSubscriptionTimestamp: DateTime - 要求が受信された時点Tracing: bool - トレースがオンかオフかを示します 利用者 Variables: IReadOnlyDictionary<string, object>void Trace(message: string) Workspace |
context.Api |
Id: stringIsCurrentRevision: boolName: stringPath: stringRevision: stringServiceUrl: IUrlVersion: string |
context.Deployment |
GatewayGatewayId: string (マネージドゲートウェイの場合は 'managed' を返します)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id: string (マネージドゲートウェイの場合は 'managed' を返します)InstanceId: string (マネージドゲートウェイの場合は 'managed' を返します)IsManaged: bool |
context.Deployment.SustainabilityInfo |
CurrentCarbonIntensity: Enum CarbonIntensityCategory |
context.GraphQL |
GraphQLArguments: IGraphQLDataObjectParent: IGraphQLDataObject使用例 |
context.LastError |
Source: stringReason: stringMessage: stringScope: stringSection: stringPath: stringPolicyId: stringcontext.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 または null のようになります。Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2Headers: IReadOnlyDictionary<string, string[]>IpAddress: stringMatchedParameters: IReadOnlyDictionary<string, string>Method: stringOriginalUrl: IUrlUrl: IUrlPrivateEndpointConnection: 要求がプライベート エンドポイント接続から来ていない場合は、IPrivateEndpointConnectionま たは null のようになります。 |
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringコンマ区切りの要求ヘッダー値を返すか、ヘッダーが見つからない場合は defaultValue を返します。 |
context.Response |
Body: IMessageBodyHeaders: IReadOnlyDictionary<string, string[]>StatusCode: intStatusReason: string |
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) |
headerName: stringdefaultValue: stringコンマ区切りの応答ヘッダー値を返すか、ヘッダーが見つからない場合は defaultValue を返します。 |
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 |
未定 |
IGroup |
Id: stringName: string |
IMessageBody |
As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument - context.Request.Body.As<T> と context.Response.Body.As<T> のメソッドを使って、指定した種類 T の要求または応答メッセージ本文を読み取ります。 - または - AsFormUrlEncodedContent(bool preserveContent = false) - context.Request.Body.AsFormUrlEncodedContent() と context.Response.Body.AsFormUrlEncodedContent() のメソッドを使って、要求または応答メッセージ本文の URL エンコードされたフォーム データを読み取り、IDictionary<string, IList<string> オブジェクトを返します。 デコードされたオブジェクトは IDictionary 操作と次の式をサポートします: ToQueryString()、JsonConvert.SerializeObject()、ToFormUrlEncodedContent(). 既定では、 As<T> と AsFormUrlEncodedContent() のメソッド:
これを回避し、本文ストリームのコピーでメソッドを実行するには、 preserveContent ポリシーの例で示すように true パラメーターを に設定します。 |
IPrivateEndpointConnection |
Name: stringGroupId: stringMemberName: string詳しくは、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: stringコンマ区切りのクエリ パラメーター値、またはパラメーターが見つからない場合は defaultValue を返します。 |
IUserIdentity |
Id: stringProvider: string |
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) |
variableName: stringdefaultValue: T型 T にキャストされた変数値を返すか、変数が見つからない場合は defaultValue を返します。このメソッドは、指定された型が返された変数の実際の型と一致しない場合に例外をスローします。 |
BasicAuthCredentials AsBasic(input: this string) |
input: string入力パラメーターに有効な HTTP 基本認証の承認要求ヘッダー値が含まれている場合、メソッドは BasicAuthCredentials 型のオブジェクトを返します。それ以外の場合、メソッドは null を返します。 |
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) |
input: stringresult: out BasicAuthCredentials入力パラメーターに要求ヘッダーに有効な HTTP 基本認証承認値が含まれている場合、メソッドは true を返し、result パラメーターには BasicAuthCredentials 型の値が含まれます。それ以外の場合、メソッドは false を返します。 |
BasicAuthCredentials |
Password: stringUserId: string |
Jwt AsJwt(input: this string) |
input: string入力パラメーターに有効な JWT 値が含まれている場合、メソッドは Jwt型のオブジェクトを返します。それ以外の場合、メソッドは nullを返します。 |
bool TryParseJwt(input: this string, result: out Jwt) |
input: stringresult: out Jwt入力パラメーターに有効な JWT 値が含まれている場合、メソッドは true を返し、結果パラメーターには Jwt型の値が含まれます。それ以外の場合、メソッドは 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: stringコンマ区切りの要求値を返すか、ヘッダーが見つからない場合は defaultValue を返します。 |
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - 暗号化対象のプレーンテキストalg - 対称暗号化アルゴリズムの名前key - 暗号化キーiv - 初期化ベクター暗号化されたプレーンテキストを返します。 |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - 暗号化対象のプレーンテキストalg - 暗号化アルゴリズム暗号化されたプレーンテキストを返します。 |
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - 暗号化対象のプレーンテキストalg - 暗号化アルゴリズムkey - 暗号化キーiv - 初期化ベクター暗号化されたプレーンテキストを返します。 |
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) |
input - 暗号化解除対象の暗号化テキストalg - 対称暗号化アルゴリズムの名前key - 暗号化キーiv - 初期化ベクタープレーンテキストを返します。 |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) |
input - 暗号化解除対象の暗号化テキストalg - 暗号化アルゴリズムプレーンテキストを返します。 |
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) |
input - 暗号化解除対象の暗号化テキストalg - 暗号化アルゴリズムkey - 暗号化キーiv - 初期化ベクタープレーンテキストを返します。 |
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) |
証明書の失効状態を確認しないで、X.509 チェーン検証を実行します。input - 証明書オブジェクト検証に成功したら true、検証に失敗したら false を返します。 |
関連するコンテンツ
ポリシーに対する処理の詳細については、次のトピックを参照してください。
- チュートリアル:API を変換および保護する
- ポリシー ステートメントとその設定の一覧に関するポリシー リファレンス
- ポリシー式
- ポリシーの設定または編集
- ポリシー構成を再利用する
- ポリシー スニペットのリポジトリ
- ポリシープレイグラウンドリポジトリ
- Azure API Management ポリシー ツールキット
- ポリシーの作成、説明、トラブルシューティングを行う Copilot のサポートを受ける
詳細情報:
- バックエンド サービスにコンテキスト情報を指定する方法をご覧ください。 この情報を指定するには、クエリ文字列パラメーターの設定ポリシーおよび HTTP ヘッダーの設定ポリシーを使用します。
- JWT を検証するポリシーを使用して、トークン クレームに基づいて操作へのアクセスを事前に承認する方法を示します。
- API トレースを使用して、ポリシーの評価方法とそれらの評価の結果を検出する方法について説明します。
-
キャッシュから取得ポリシーおよびキャッシュに格納ポリシーの式を使用して、API Management 応答のキャッシュを構成する方法をご覧ください。 バックエンド サービスの
Cache-Controlディレクティブによって指定されたバックエンド サービスの応答キャッシュ時間と一致するように設定しています。 - コンテンツのフィルター処理を実行する方法をご覧ください。 制御フロー ポリシーおよび本文設定ポリシーを使用して、バックエンドから受信した応答からデータ要素を削除しています。
- ポリシー ステートメントをダウンロードするには、api-management-samples/policies GitHub リポジトリをご覧ください。