적용 대상: 모든 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 |
(생성자), 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, , TryParseToString |
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, TryParseToString |
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, , 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 |
(생성자), 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: IApiDeploymentElapsed: 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(관리 게이트웨이에 대해 '관리'를 반환)Region: stringServiceId: stringServiceName: stringSustainabilityInfoCertificates: IReadOnlyDictionary<string, X509Certificate2> |
context.Deployment.Gateway |
Id: string(관리 게이트웨이에 대해 '관리'를 반환)InstanceId: string(관리 게이트웨이에 대해 '관리'를 반환)IsManaged: bool |
context.Deployment.SustainabilityInfo |
CurrentCarbonIntensity: Enum 탄소 강도 카테고리 |
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: TT 형식으로 캐스팅되는 변수 값 또는 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를 반환하고 결과 매개 변수는 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 리포지토리를 참조하세요.