Share via


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 정책에서든 특성 값 또는 텍스트 값으로 사용될 수 있습니다.

Important

정책이 정의될 때 정책 식은 제한된 검증만을 갖습니다. 식은 런타임에 게이트웨이에 의해 실행됩니다. 정책 식에 의해 생성된 모든 예외는 런타임 오류를 발생시킵니다.

정책 식에 허용된 .NET Framework 형식

다음 표에는 정책 식에 허용되는 .NET Framework 형식 및 멤버가 나와 있습니다.

Type 지원되는 멤버
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 (생성자), 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 모두
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 (생성자), 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 변수는 모든 정책 에서 암시적으로 사용할 수 있습니다. 멤버:

  • API 요청응답, 관련 속성과 관련된 정보를 제공합니다.
  • 모두 읽기 전용입니다.
컨텍스트 변수 허용된 메서드, 속성 및 매개 변수 값
context Api: IApi

Deployment

Elapsed: TimeSpan - Timestamp 값과 현재 시간 사이의 시간 간격

GraphQL

LastError

Operation

Request

RequestId: Guid - 고유 요청 식별자

Response

Subscription

Timestamp: DateTime - 요청이 수신된 시점

Tracing: bool - 추적의 설정 여부를 나타냅니다.

사용자

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(관리 게이트웨이에 대해 '관리'를 반환)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string(관리 게이트웨이에 대해 '관리'를 반환)

InstanceId: string(관리 게이트웨이에 대해 '관리'를 반환)

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 미정

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를 반환하고 결과 매개 변수는 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 검사기 추적을 사용하여 정책을 평가하는 방법 및 평가 결과를 확인하는 방법을 참조하세요.
  • 캐시에서 가져오기캐시에 저장 정책이 있는 식을 사용하여 API Management 응답 캐싱을 구성하는 방법을 참조합니다. 백 엔드 서비스의 Cache-Control 지시문에 지정된 대로 백 엔드 서비스의 응답 캐싱과 일치하는 기간을 설정합니다.
  • 콘텐츠 필터링을 수행하는 방법을 참조합니다. 흐름 제어본문 설정 정책을 사용하여 백 엔드에서 받은 응답의 데이터 요소를 제거합니다.
  • 정책 명령문을 다운로드하려면 api-management-samples/policies GitHub 리포지토리를 참조하세요.