API Management ポリシー式

適用対象: すべての 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 の型とメンバーの一覧です。

Type サポートされているメンバー
Newtonsoft.Json.Formatting すべて
Newtonsoft.Json.JsonConvert SerializeObjectDeserializeObject
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)、AddAddDaysAddHoursAddMillisecondsAddMinutesAddMonthsAddSecondsAddTicksAddYearsDateDayDayOfWeekDayOfYearDaysInMonthHourIsDaylightSavingTimeIsLeapYearMaxValueMillisecondMinuteMinValueMonthNowParseSecondSubtractTicksTimeOfDayTodayToStringUtcNowYear
System.DateTimeKind Utc
System.DateTimeOffset すべて
System.Decimal すべて
System.Double すべて
System.Enum ParseTryParseToString
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 AddressFamilyEqualsGetAddressBytesIsLoopbackParseTryParseToString
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 すべて
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 IndexLengthValue
System.Text.RegularExpressions.CaptureCollection CountItem
System.Text.RegularExpressions.Group CapturesSuccess
System.Text.RegularExpressions.GroupCollection CountItem
System.Text.RegularExpressions.Match EmptyGroupsResult
System.Text.RegularExpressions.Regex (Constructor)、IsMatchMatchMatchesReplaceUnescapeSplit
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 All

コンテキストの変数

context 変数は、暗黙的にすべてのポリシーで使用できます。 そのメンバーは次のようになります。

  • API の要求応答、および関連するプロパティに関連する情報を提供します。
  • すべて読み取り専用です。
コンテキスト変数 使用可能なメソッド、プロパティ、パラメーターの値
context Api: IApi

Deployment

経過時間: TimeSpan - Timestampの値と現在の時刻の間の時間間隔

GraphQL

LastError

Operation

Request

RequestId: Guid - 一意の要求識別子

Response

Subscription

Timestamp: DateTime - 要求が受信された時点

Tracing: bool - トレースがオンかオフかを示します

User

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 (マネージドゲートウェイの場合は 'managed' を返します)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (マネージドゲートウェイの場合は 'managed' を返します)

InstanceId: string (マネージドゲートウェイの場合は 'managed' を返します)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

使用例
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

context.LastError の詳細については、「エラー処理」を参照してください。
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 または null のようになります。

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: 要求がプライベート エンドポイント接続から来ていない場合は、IPrivateEndpointConnectionま たは null のようになります。
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

コンマ区切りの要求ヘッダー値を返すか、ヘッダーが見つからない場合は defaultValue を返します。
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

コンマ区切りの応答ヘッダー値を返すか、ヘッダーが見つからない場合は defaultValue を返します。
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 TBD

IGroup Id: string

Name: 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() のメソッド:
  • 元のメッセージ本文ストリームを使います。
  • 戻った後は使用不可とレンダリングします。

これを回避し、本文ストリームのコピーでメソッドを実行するには、set-body ポリシーの例で示すように preserveContent パラメーターを true に設定します。
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

詳しくは、REST API に関するページをご覧ください。
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

コンマ区切りのクエリ パラメーター値、またはパラメーターが見つからない場合は defaultValue を返します。
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

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

defaultValue: T

T にキャストされた変数値を返すか、変数が見つからない場合は defaultValue を返します。

このメソッドは、指定された型が返された変数の実際の型と一致しない場合に例外をスローします。
BasicAuthCredentials AsBasic(input: this string) input: string

入力パラメーターに有効な HTTP 基本認証の承認要求ヘッダー値が含まれている場合、メソッドは BasicAuthCredentials 型のオブジェクトを返します。それ以外の場合、メソッドは null を返します。
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

入力パラメーターに要求ヘッダーに有効な HTTP 基本認証承認値が含まれている場合、メソッドは true を返し、result パラメーターには BasicAuthCredentials 型の値が含まれます。それ以外の場合、メソッドは false を返します。
BasicAuthCredentials Password: string

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

入力パラメーターに有効な JWT トークン値が含まれている場合、メソッドは Jwt 型のオブジェクトを返します。それ以外の場合、メソッドは null を返します。
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

入力パラメーターに有効な JWT トークン値が含まれている場合、メソッドは true を返し、結果パラメーターには Jwt 型の値が含まれます。それ以外の場合、メソッドは 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

コンマ区切りの要求値を返すか、ヘッダーが見つからない場合は 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 を返します。

ポリシーを使用する方法の詳細については、次のトピックを参照してください。

詳細情報:

  • バックエンド サービスにコンテキスト情報を指定する方法をご覧ください。 この情報を指定するには、クエリ文字列パラメーターの設定ポリシーおよび HTTP ヘッダーの設定ポリシーを使用します。
  • JWT を検証するポリシーを使用して、トークン クレームに基づいて操作へのアクセスを事前に承認する方法を示します。
  • API Inspector トレースによってポリシーの評価方法と評価結果を検出する方法を示します。
  • キャッシュから取得ポリシーおよびキャッシュに格納ポリシーの式を使用して、API Management 応答のキャッシュを構成する方法をご覧ください。 バックエンド サービスの Cache-Control ディレクティブによって指定されたバックエンド サービスの応答キャッシュ時間と一致するように設定しています。
  • コンテンツのフィルター処理を実行する方法をご覧ください。 制御フロー ポリシーおよび本文設定ポリシーを使用して、バックエンドから受信した応答からデータ要素を削除しています。
  • ポリシー ステートメントをダウンロードするには、api-management-samples/policies GitHub リポジトリをご覧ください。