API 管理高级策略API Management advanced policies

本主题提供以下 API 管理策略的参考。This topic provides a reference for the following API Management policies. 有关添加和配置策略的信息,请参阅 API 管理中的策略For information on adding and configuring policies, see Policies in API Management.

高级策略Advanced policies

  • 控制流 - 根据布尔表达式的求值结果,有条件地应用策略语句。Control flow - Conditionally applies policy statements based on the results of the evaluation of Boolean expressions.
  • 转发请求 - 将请求转发到后端服务。Forward request - Forwards the request to the backend service.
  • 限制并发 - 阻止括住的策略一次执行超过指定数量的请求。Limit concurrency - Prevents enclosed policies from executing by more than the specified number of requests at a time.
  • 记录到事件中心 - 将指定格式的消息发送到记录器实体定义的事件中心。Log to Event Hub - Sends messages in the specified format to an Event Hub defined by a Logger entity.
  • 模拟响应 - 中止管道执行,将模拟的响应直接返回给调用方。Mock response - Aborts pipeline execution and returns a mocked response directly to the caller.
  • 重试 - 重试执行括住的策略语句,直到符合条件为止。Retry - Retries execution of the enclosed policy statements, if and until the condition is met. 系统会按指定的时间间隔重复执行,直到达到指定的重试计数为止。Execution will repeat at the specified time intervals and up to the specified retry count.
  • 返回响应 - 中止管道执行,将指定的响应直接返回给调用方。Return response - Aborts pipeline execution and returns the specified response directly to the caller.
  • 发送单向请求 - 将请求发送到指定的 URL,无需等待响应。Send one way request - Sends a request to the specified URL without waiting for a response.
  • 发送请求 - 将请求发送到指定的 URL。Send request - Sends a request to the specified URL.
  • 设置 HTTP 代理 - 允许通过 HTTP 代理路由转发请求。Set HTTP proxy - Allows you to route forwarded requests via an HTTP proxy.
  • 设置请求方法 - 允许更改请求的 HTTP 方法。Set request method - Allows you to change the HTTP method for a request.
  • 设置状态代码 - 将 HTTP 状态代码更改为指定的值。Set status code - Changes the HTTP status code to the specified value.
  • 设置变量 - 保存命名上下文变量中的值供以后访问。Set variable - Persists a value in a named context variable for later access.
  • 跟踪 - 将自定义跟踪添加到 API 检查器输出、Application Insights 遥测和资源日志。Trace - Adds custom traces into the API Inspector output, Application Insights telemetries, and Resource Logs.
  • 等待 - 在继续下一步之前,等待括住的发送请求从缓存中获取值控制流策略完成。Wait - Waits for enclosed Send request, Get value from cache, or Control flow policies to complete before proceeding.

控制流Control flow

choose 策略根据布尔表达式的求值结果应用括住的策略语句,类似于编程语言中的 if-then-else 或开关构造。The choose policy applies enclosed policy statements based on the outcome of evaluation of Boolean expressions, similar to an if-then-else or a switch construct in a programming language.

策略语句Policy statement

<choose>
    <when condition="Boolean expression | Boolean constant">
        <!— one or more policy statements to be applied if the above condition is true  -->
    </when>
    <when condition="Boolean expression | Boolean constant">
        <!— one or more policy statements to be applied if the above condition is true  -->
    </when>
    <otherwise>
        <!— one or more policy statements to be applied if none of the above conditions are true  -->
</otherwise>
</choose>

控制流策略必须包含至少一个 <when/> 元素。The control flow policy must contain at least one <when/> element. <otherwise/> 元素是可选的。The <otherwise/> element is optional. <when/> 元素中的条件根据其在策略中的出现顺序求值。Conditions in <when/> elements are evaluated in order of their appearance within the policy. 将应用条件属性等于 true 的第一个 <when/> 元素中括住的策略语句。Policy statement(s) enclosed within the first <when/> element with condition attribute equals true will be applied. 在所有 <when/> 元素条件属性为 false 的情况下,将应用 <otherwise/> 元素中括住的策略(如果存在)。Policies enclosed within the <otherwise/> element, if present, will be applied if all of the <when/> element condition attributes are false.

示例Examples

示例Example

以下示例演示 set-variable 策略和两项控制流策略。The following example demonstrates a set-variable policy and two control flow policies.

此 set-variable 策略位于入站节,用于创建 isMobile 布尔上下文变量,该变量在 User-Agent 请求标头包含文本 iPadiPhone 的情况下设置为 true。The set variable policy is in the inbound section and creates an isMobile Boolean context variable that is set to true if the User-Agent request header contains the text iPad or iPhone.

第一项控制流策略也位于入站节,并会根据 isMobile 上下文变量的值有条件地应用两项设置查询字符串参数策略之一。The first control flow policy is also in the inbound section, and conditionally applies one of two Set query string parameter policies depending on the value of the isMobile context variable.

第二项控制流策略位于出站节,并会在 isMobile 设置为 true 时有条件地应用将 XML 转换为 JSON 策略。The second control flow policy is in the outbound section and conditionally applies the Convert XML to JSON policy when isMobile is set to true.

<policies>
    <inbound>
        <set-variable name="isMobile" value="@(context.Request.Headers["User-Agent"].Contains("iPad") || context.Request.Headers["User-Agent"].Contains("iPhone"))" />
        <base />
        <choose>
            <when condition="@(context.Variables.GetValueOrDefault<bool>("isMobile"))">
                <set-query-parameter name="mobile" exists-action="override">
                    <value>true</value>
                </set-query-parameter>
            </when>
            <otherwise>
                <set-query-parameter name="mobile" exists-action="override">
                    <value>false</value>
                </set-query-parameter>
            </otherwise>
        </choose>
    </inbound>
    <outbound>
        <base />
        <choose>
            <when condition="@(context.Variables.GetValueOrDefault<bool>("isMobile"))">
                <xml-to-json kind="direct" apply="always" consider-accept-header="false"/>
            </when>
        </choose>
    </outbound>
</policies>

示例Example

以下示例演示了如何进行内容筛选,方法是:在使用 Starter 产品时删除从后端服务接收的响应中的数据元素。This example shows how to perform content filtering by removing data elements from the response received from the backend service when using the Starter product. 有关配置和使用此策略的演示,请参阅 Cloud Cover 第 177 集:更多的 API 管理功能与 VLAD Vinogradsky 并快进到 34:30。For a demonstration of configuring and using this policy, see Cloud Cover Episode 177: More API Management Features with Vlad Vinogradsky and fast-forward to 34:30. 若要大致了解用于此演示的 Dark Sky Forecast API,请从 31:50 开始观看。Start at 31:50 to see an overview of The Dark Sky Forecast API used for this demo.

<!-- Copy this snippet into the outbound section to remove a number of data elements from the response received from the backend service based on the name of the api product -->
<choose>
  <when condition="@(context.Response.StatusCode == 200 && context.Product.Name.Equals("Starter"))">
    <set-body>@{
        var response = context.Response.Body.As<JObject>();
        foreach (var key in new [] {"minutely", "hourly", "daily", "flags"}) {
          response.Property (key).Remove ();
        }
        return response.ToString();
      }
    </set-body>
  </when>
</choose>

元素Elements

元素Element 描述Description 必须Required
choosechoose 根元素。Root element. Yes
whenwhen 条件,用于 choose 策略的 ififelse 部分。The condition to use for the if or ifelse parts of the choose policy. 如果 choose 策略包含多个 when 节,则按顺序对其求值。If the choose policy has multiple when sections, they are evaluated sequentially. 一旦 when 元素的 condition 的求值结果为 true,不再对 when 条件求值。Once the condition of a when element evaluates to true, no further when conditions are evaluated. Yes
otherwiseotherwise 包含策略代码片段,该片段在没有 when 条件的求值结果为 true 的情况下使用。Contains the policy snippet to be used if none of the when conditions evaluate to true. No

属性Attributes

属性Attribute 描述Description 必须Required
condition="布尔表达式 | 布尔常量"condition="Boolean expression | Boolean constant" 对包含 when 的策略语句求值时需求值的布尔表达式或常量。The Boolean expression or constant to evaluated when the containing when policy statement is evaluated. Yes

用法Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

转发请求Forward request

forward-request 策略将传入请求转发到请求上下文中指定的后端服务。The forward-request policy forwards the incoming request to the backend service specified in the request context. 后端服务 URL 在 API 设置中指定,可以使用设置后端服务策略进行更改。The backend service URL is specified in the API settings and can be changed using the set backend service policy.

备注

删除此策略之后,请求就不会转发到后端服务。一旦成功完成入站节中的策略,就会立即对出站节中的策略求值。Removing this policy results in the request not being forwarded to the backend service and the policies in the outbound section are evaluated immediately upon the successful completion of the policies in the inbound section.

策略语句Policy statement

<forward-request timeout="time in seconds" follow-redirects="false | true" buffer-request-body="false | true" fail-on-error-status-code="false | true"/>

示例Examples

示例Example

以下 API 级策略将所有 API 请求都转发到后端服务,超时间隔设置为 60 秒。The following API level policy forwards all API requests to the backend service with a timeout interval of 60 seconds.

<!-- api level -->
<policies>
    <inbound>
        <base/>
    </inbound>
    <backend>
        <forward-request timeout="60"/>
    </backend>
    <outbound>
        <base/>
    </outbound>
</policies>

示例Example

以下操作级策略使用 base 元素,从父 API 级范围继承后端策略。This operation level policy uses the base element to inherit the backend policy from the parent API level scope.

<!-- operation level -->
<policies>
    <inbound>
        <base/>
    </inbound>
    <backend>
        <base/>
    </backend>
    <outbound>
        <base/>
    </outbound>
</policies>

示例Example

以下操作级策略显式将所有请求转发到后端服务,超时设置为 120 秒,不继承父 API 级后端策略。This operation level policy explicitly forwards all requests to the backend service with a timeout of 120 and does not inherit the parent API level backend policy. 如果后端服务以 400 到 599(含)之间的错误状态代码响应,则将触发 on-error 节。If the backend service responds with a error status code from 400 to 599 inclusive, on-error section will be triggered.

<!-- operation level -->
<policies>
    <inbound>
        <base/>
    </inbound>
    <backend>
        <forward-request timeout="120" fail-on-error-status-code="true" />
        <!-- effective policy. note the absence of <base/> -->
    </backend>
    <outbound>
        <base/>
    </outbound>
</policies>

示例Example

以下操作级策略不将请求转发到后端服务。This operation level policy does not forward requests to the backend service.

<!-- operation level -->
<policies>
    <inbound>
        <base/>
    </inbound>
    <backend>
        <!-- no forwarding to backend -->
    </backend>
    <outbound>
        <base/>
    </outbound>
</policies>

元素Elements

元素Element 描述Description 必须Required
forward-requestforward-request 根元素。Root element. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
timeout="整数"timeout="integer" 在引发超时错误之前,等待后端服务返回 HTTP 响应标头的时间量(秒)。The amount of time in seconds to wait for the HTTP response headers to be returned by the backend service before a timeout error is raised. 最小值为 0 秒。Minimum value is 0 seconds. 大于 240 秒的值可能不会被遵守,因为底层网络基础设施在此时间后可能会丢弃闲置的连接。Values greater than 240 seconds may not be honored as the underlying network infrastructure can drop idle connections after this time. No None
follow-redirects="false | true"follow-redirects="false | true" 指定是由网关执行从后端服务的重定向,还是将重定向返回到调用方。Specifies whether redirects from the backend service are followed by the gateway or returned to the caller. No falsefalse
buffer-request-body="false | true"buffer-request-body="false | true" 设置为“true”时,请求将被缓冲,并将在重试时重新使用。When set to "true" request is buffered and will be reused on retry. No falsefalse
fail-on-error-status-code="false | true"fail-on-error-status-code="false | true" 设置为 true 时触发 400 到 599(含)范围的响应代码的 on-error 节。When set to true triggers on-error section for response codes in the range from 400 to 599 inclusive. No falsefalse

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 后端Policy sections: backend
  • 策略范围: 所有范围Policy scopes: all scopes

限制并发Limit concurrency

limit-concurrency 策略阻止括住的策略在任意时间执行超过指定数量的请求。The limit-concurrency policy prevents enclosed policies from executing by more than the specified number of requests at any time. 超过该数量后,新请求将立即失败并显示“429 请求过多”状态代码。Upon exceeding that number, new requests will fail immediately with 429 Too Many Requests status code.

策略语句Policy statement

<limit-concurrency key="expression" max-count="number">
        <!— nested policy statements -->
</limit-concurrency>

示例Examples

示例Example

下例演示了如何基于上下文变量的值限制转发到后端的请求数。The following example demonstrates how to limit number of requests forwarded to a backend based on the value of a context variable.

<policies>
  <inbound>…</inbound>
  <backend>
    <limit-concurrency key="@((string)context.Variables["connectionId"])" max-count="3">
      <forward-request timeout="120"/>
    </limit-concurrency>
  </backend>
  <outbound>…</outbound>
</policies>

元素Elements

元素Element 描述Description 必须Required
limit-concurrencylimit-concurrency 根元素。Root element. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
keykey 一个字符串。A string. 允许使用表达式。Expression allowed. 指定并发作用域。Specifies the concurrency scope. 可以由多个策略共享。Can be shared by multiple policies. Yes 空值N/A
max-countmax-count 一个整数。An integer. 指定允许输入策略的最大请求数。Specifies a maximum number of requests that are allowed to enter the policy. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

记录到事件中心Log to Event Hub

log-to-eventhub 策略将指定格式的消息发送到记录器实体定义的事件中心。The log-to-eventhub policy sends messages in the specified format to an Event Hub defined by a Logger entity. 从名称可以看出,此策略用于保存所选请求或响应上下文信息,以便进行联机或脱机分析。As its name implies, the policy is used for saving selected request or response context information for online or offline analysis.

备注

如需配置事件中心和记录事件的分步指南,请参阅如何在 Azure API 管理中将事件记录到 Azure 事件中心For a step-by-step guide on configuring an event hub and logging events, see How to log API Management events with Azure Event Hubs.

策略语句Policy statement

<log-to-eventhub logger-id="id of the logger entity" partition-id="index of the partition where messages are sent" partition-key="value used for partition assignment">
  Expression returning a string to be logged
</log-to-eventhub>

示例Example

可以将任何字符串用作要记录到事件中心的值。Any string can be used as the value to be logged in Event Hubs. 在以下示例中,所有入站调用的日期和时间、部署服务名称、请求 ID、IP 地址和操作名称都记录到以 contoso-logger ID 注册的事件中心记录器In this example the date and time, deployment service name, request ID, IP address, and operation name for all inbound calls are logged to the event hub Logger registered with the contoso-logger ID

<policies>
  <inbound>
    <log-to-eventhub logger-id ='contoso-logger'>
      @( string.Join(",", DateTime.UtcNow, context.Deployment.ServiceName, context.RequestId, context.Request.IpAddress, context.Operation.Name) )
    </log-to-eventhub>
  </inbound>
  <outbound>
  </outbound>
</policies>

元素Elements

元素Element 描述Description 必须Required
log-to-eventhublog-to-eventhub 根元素。Root element. 此元素的值是要记录到事件中心的字符串。The value of this element is the string to log to your event hub. Yes

属性Attributes

属性Attribute 描述Description 必须Required
logger-idlogger-id 注册到 API 管理服务的记录器的 ID。The ID of the Logger registered with your API Management service. Yes
partition-idpartition-id 指定在其中发送消息的分区的索引。Specifies the index of the partition where messages are sent. 可选。Optional. 如果使用 partition-key,则不能使用此属性。This attribute may not be used if partition-key is used.
partition-keypartition-key 指定在发送消息时用于分区分配的值。Specifies the value used for partition assignment when messages are sent. 可选。Optional. 如果使用 partition-id,则不能使用此属性。This attribute may not be used if partition-id is used.

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

模拟响应Mock response

正如其名所示,mock-response 用于模拟 API 和操作。The mock-response, as the name implies, is used to mock APIs and operations. 它会中止正常的管道执行,并将模拟的响应返回给调用方。It aborts normal pipeline execution and returns a mocked response to the caller. 该策略始终尝试返回保真度最高的响应。The policy always tries to return responses of highest fidelity. 它首选响应内容示例(若可用)。It prefers response content examples, whenever available. 若提供架构而不提供示例,它将从架构生成示例响应。It generates sample responses from schemas, when schemas are provided and examples are not. 如果既找不到示例又找不到架构,则返回无内容的响应。If neither examples or schemas are found, responses with no content are returned.

策略语句Policy statement

<mock-response status-code="code" content-type="media type"/>

示例Examples

<!-- Returns 200 OK status code. Content is based on an example or schema, if provided for this
status code. First found content type is used. If no example or schema is found, the content is empty. -->
<mock-response/>

<!-- Returns 200 OK status code. Content is based on an example or schema, if provided for this
status code and media type. If no example or schema found, the content is empty. -->
<mock-response status-code='200' content-type='application/json'/>

元素Elements

元素Element 描述Description 必须Required
mock-responsemock-response 根元素。Root element. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
status-codestatus-code 指定响应状态代码,并用于选择相应的示例或架构。Specifies response status code and is used to select corresponding example or schema. No 200200
content-typecontent-type 指定 Content-Type 响应标头值,并用于选择相应的示例或架构。Specifies Content-Type response header value and is used to select corresponding example or schema. No None

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、错误时Policy sections: inbound, outbound, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

重试Retry

retry 策略会执行其子策略一次,并重新尝试执行,直至重试 condition 变为 false,或者重试 count 为零。The retry policy executes its child policies once and then retries their execution until the retry condition becomes false or retry count is exhausted.

策略语句Policy statement


<retry
    condition="boolean expression or literal"
    count="number of retry attempts"
    interval="retry interval in seconds"
    max-interval="maximum retry interval in seconds"
    delta="retry interval delta in seconds"
    first-fast-retry="boolean expression or literal">
        <!-- One or more child policies. No restrictions -->
</retry>

示例Example

在以下示例中,请求转发最高可使用指数重试算法重试 10 次。In the following example, request forwarding is retried up to ten times using an exponential retry algorithm. 由于 first-fast-retry 设置为 false,所有重试都必须遵循指数重试算法。Since first-fast-retry is set to false, all retry attempts are subject to the exponential retry algorithm.


<retry
    condition="@(context.Response.StatusCode == 500)"
    count="10"
    interval="10"
    max-interval="100"
    delta="10"
    first-fast-retry="false">
        <forward-request buffer-request-body="true" />
</retry>

元素Elements

元素Element 描述Description 必须Required
retryretry 根元素。Root element. 可能包含任何可充当其子元素的其他策略。May contain any other policies as its child elements. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
conditioncondition 一个布尔文本或表达式,指定是应停止重试 (false) 还是应继续重试 (true)。A boolean literal or expression specifying if retries should be stopped (false) or continued (true). Yes 空值N/A
countcount 一个正数,指定进行尝试时的最大重试次数。A positive number specifying the maximum number of retries to attempt. Yes 空值N/A
intervalinterval 一个以秒为单位的正数,指定两次重试之间的等待时间。A positive number in seconds specifying the wait interval between the retry attempts. Yes 空值N/A
max-intervalmax-interval 一个以秒为单位的正数,指定两次重试之间的最长等待时间,A positive number in seconds specifying the maximum wait interval between the retry attempts. 用于实现指数重试算法。It is used to implement an exponential retry algorithm. No 空值N/A
deltadelta 一个以秒为单位的正数,指定等待时间间隔增量,A positive number in seconds specifying the wait interval increment. 用于实现线性和指数重试算法。It is used to implement the linear and exponential retry algorithms. No 空值N/A
first-fast-retryfirst-fast-retry 如果设置为 true,则会立即执行首次重试。If set to true , the first retry attempt is performed immediately. No false

备注

仅指定 interval 时,则会执行固定时间间隔的重试。When only the interval is specified, fixed interval retries are performed. 仅指定 intervaldelta 时,将使用线性时间间隔重试算法,其中,两次重试之间的等待时间按以下公式计算:interval + (count - 1)*deltaWhen only the interval and delta are specified, a linear interval retry algorithm is used, where wait time between retries is calculated according the following formula - interval + (count - 1)*delta. 指定 intervalmax-intervaldelta 时,将应用指数时间间隔重试算法,其中,两次重试之间的等待时间根据以下公式从 interval 值呈指数增长到 max-interval 值:min(interval + (2^count - 1) * random(delta * 0.8, delta * 1.2), max-interval)When the interval, max-interval and delta are specified, exponential interval retry algorithm is applied, where the wait time between the retries is growing exponentially from the value of interval to the value max-interval according to the following formula - min(interval + (2^count - 1) * random(delta * 0.8, delta * 1.2), max-interval).

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes . 请注意,此策略会继承子策略使用限制。Note that child policy usage restrictions will be inherited by this policy.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

返回响应Return response

return-response 策略会中止管道执行,为调用方返回默认响应或自定义响应。The return-response policy aborts pipeline execution and returns either a default or custom response to the caller. 默认响应为200 OK,无正文。Default response is 200 OK with no body. 可以通过上下文变量或策略语句指定自定义响应。Custom response can be specified via a context variable or policy statements. 二者都提供时,会通过策略语句对上下文变量中包含的响应进行修改,然后再将其返回给调用方。When both are provided, the response contained within the context variable is modified by the policy statements before being returned to the caller.

策略语句Policy statement

<return-response response-variable-name="existing context variable">
  <set-header/>
  <set-body/>
  <set-status/>
</return-response>

示例Example

<return-response>
   <set-status code="401" reason="Unauthorized"/>
   <set-header name="WWW-Authenticate" exists-action="override">
      <value>Bearer error="invalid_token"</value>
   </set-header>
</return-response>

元素Elements

元素Element 描述Description 必须Required
return-responsereturn-response 根元素。Root element. Yes
set-headerset-header set-header 策略语句。A set-header policy statement. No
set-bodyset-body set-body 策略语句。A set-body policy statement. No
set-statusset-status set-status 策略语句。A set-status policy statement. No

属性Attributes

属性Attribute 描述Description 必须Required
response-variable-nameresponse-variable-name 上下文变量的名称,该变量引用自特定的策略(例如上游 send-request 策略)且包含 Response 对象The name of the context variable referenced from, for example, an upstream send-request policy and containing a Response object 可选。Optional.

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

发送单向请求Send one way request

send-one-way-request 策略将提供的请求发送到指定的 URL,无需等待响应。The send-one-way-request policy sends the provided request to the specified URL without waiting for a response.

策略语句Policy statement

<send-one-way-request mode="new | copy">
  <url>...</url>
  <method>...</method>
  <header name="" exists-action="override | skip | append | delete">...</header>
  <body>...</body>
  <authentication-certificate thumbprint="thumbprint" />
</send-one-way-request>

示例Example

以下示例策略以示例方式演示了在 HTTP 响应代码大于或等于 500 的情况下,如何使用 send-one-way-request 策略将消息发送到 Slack 聊天室。This sample policy shows an example of using the send-one-way-request policy to send a message to a Slack chat room if the HTTP response code is greater than or equal to 500. 有关此示例的详细信息,请参阅通过 Azure API 管理服务使用外部服务For more information on this sample, see Using external services from the Azure API Management service.

<choose>
    <when condition="@(context.Response.StatusCode >= 500)">
      <send-one-way-request mode="new">
        <set-url>https://hooks.slack.com/services/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</set-url>
        <set-method>POST</set-method>
        <set-body>@{
                return new JObject(
                        new JProperty("username","APIM Alert"),
                        new JProperty("icon_emoji", ":ghost:"),
                        new JProperty("text", String.Format("{0} {1}\nHost: {2}\n{3} {4}\n User: {5}",
                                                context.Request.Method,
                                                context.Request.Url.Path + context.Request.Url.QueryString,
                                                context.Request.Url.Host,
                                                context.Response.StatusCode,
                                                context.Response.StatusReason,
                                                context.User.Email
                                                ))
                        ).ToString();
            }</set-body>
      </send-one-way-request>
    </when>
</choose>

元素Elements

元素Element 描述Description 必须Required
send-one-way-requestsend-one-way-request 根元素。Root element. Yes
urlurl 请求的 URL。The URL of the request. 如果 mode=copy,则为否;否则为是。No if mode=copy; otherwise yes.
methodmethod 用于请求的 HTTP 方法。The HTTP method for the request. 如果 mode=copy,则为否;否则为是。No if mode=copy; otherwise yes.
标头的值开始缓存响应header 请求标头。Request header. 将多个标头元素用于多个请求标头。Use multiple header elements for multiple request headers. No
bodybody 请求正文。The request body. No
authentication-certificateauthentication-certificate 用于客户端身份验证的证书Certificate to use for client authentication No

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
mode="string"mode="string" 确定请求是新请求还是当前请求的副本。Determines whether this is a new request or a copy of the current request. 在出站模式下,mode=copy 不会初始化请求正文。In outbound mode, mode=copy does not initialize the request body. No 新建New
namename 指定要设置的标头的名称。Specifies the name of the header to be set. Yes 空值N/A
exists-actionexists-action 指定当标头已指定时要执行的操作。Specifies what action to take when the header is already specified. 此属性必须具有下列值之一。This attribute must have one of the following values.

- override - 替换现有标头的值。- override - replaces the value of the existing header.
- skip - 不替换现有标头值。- skip - does not replace the existing header value.
- append - 将值追加到现有标头值。- append - appends the value to the existing header value.
- delete - 从请求中删除标头。- delete - removes the header from the request.

如果设置为 override,则登记多个同名的条目会导致根据所有条目(将多次列出)设置标头;结果中只会设置列出的值。When set to override enlisting multiple entries with the same name results in the header being set according to all entries (which will be listed multiple times); only listed values will be set in the result.
No overrideoverride

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

发送请求Send request

send-request 策略将提供的请求发送至指定 URL,等待时间不超过设置的超时值。The send-request policy sends the provided request to the specified URL, waiting no longer than the set timeout value.

策略语句Policy statement

<send-request mode="new|copy" response-variable-name="" timeout="60 sec" ignore-error
="false|true">
  <set-url>...</set-url>
  <set-method>...</set-method>
  <set-header name="" exists-action="override|skip|append|delete">...</set-header>
  <set-body>...</set-body>
  <authentication-certificate thumbprint="thumbprint" />
</send-request>

示例Example

以下示例演示了如何通过授权服务器验证引用令牌。This example shows one way to verify a reference token with an authorization server. 有关此示例的详细信息,请参阅通过 Azure API 管理服务使用外部服务For more information on this sample, see Using external services from the Azure API Management service.

<inbound>
  <!-- Extract Token from Authorization header parameter -->
  <set-variable name="token" value="@(context.Request.Headers.GetValueOrDefault("Authorization","scheme param").Split(' ').Last())" />

  <!-- Send request to Token Server to validate token (see RFC 7662) -->
  <send-request mode="new" response-variable-name="tokenstate" timeout="20" ignore-error="true">
    <set-url>https://microsoft-apiappec990ad4c76641c6aea22f566efc5a4e.chinacloudsites.cn/introspection</set-url>
    <set-method>POST</set-method>
    <set-header name="Authorization" exists-action="override">
      <value>basic dXNlcm5hbWU6cGFzc3dvcmQ=</value>
    </set-header>
    <set-header name="Content-Type" exists-action="override">
      <value>application/x-www-form-urlencoded</value>
    </set-header>
    <set-body>@($"token={(string)context.Variables["token"]}")</set-body>
  </send-request>

  <choose>
        <!-- Check active property in response -->
        <when condition="@((bool)((IResponse)context.Variables["tokenstate"]).Body.As<JObject>()["active"] == false)">
            <!-- Return 401 Unauthorized with http-problem payload -->
            <return-response>
                <set-status code="401" reason="Unauthorized" />
                <set-header name="WWW-Authenticate" exists-action="override">
                    <value>Bearer error="invalid_token"</value>
                </set-header>
            </return-response>
        </when>
    </choose>
  <base />
</inbound>

元素Elements

元素Element 描述Description 必须Required
send-requestsend-request 根元素。Root element. Yes
urlurl 请求的 URL。The URL of the request. 如果 mode=copy,则为否;否则为是。No if mode=copy; otherwise yes.
methodmethod 用于请求的 HTTP 方法。The HTTP method for the request. 如果 mode=copy,则为否;否则为是。No if mode=copy; otherwise yes.
标头的值开始缓存响应header 请求标头。Request header. 将多个标头元素用于多个请求标头。Use multiple header elements for multiple request headers. No
bodybody 请求正文。The request body. No
authentication-certificateauthentication-certificate 用于客户端身份验证的证书Certificate to use for client authentication No

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
mode="string"mode="string" 确定请求是新请求还是当前请求的副本。Determines whether this is a new request or a copy of the current request. 在出站模式下,mode=copy 不会初始化请求正文。In outbound mode, mode=copy does not initialize the request body. No 新建New
response-variable-name="string"response-variable-name="string" 将收到响应对象的上下文变量的名称。The name of context variable that will receive a response object. 如果该变量不存在,则将在成功执行策略时创建该变量,并且可通过 context.Variable 集合访问该变量。If the variable doesn't exist, it will be created upon successful execution of the policy and will become accessible via context.Variable collection. Yes 空值N/A
timeout="整数"timeout="integer" 以秒为单位的超时间隔,此时间过后对 URL 的调用会失败。The timeout interval in seconds before the call to the URL fails. No 6060
ignore-errorignore-error 如果为 true,请求会导致错误:If true and the request results in an error:

- 如果 response-variable-name 已指定,则其中会包含 null 值。- If response-variable-name was specified it will contain a null value.
- 如果 response-variable-name 未指定,则不会更新 context.Request。- If response-variable-name was not specified, context.Request will not be updated.
No falsefalse
namename 指定要设置的标头的名称。Specifies the name of the header to be set. Yes 空值N/A
exists-actionexists-action 指定当标头已指定时要执行的操作。Specifies what action to take when the header is already specified. 此属性必须具有下列值之一。This attribute must have one of the following values.

- override - 替换现有标头的值。- override - replaces the value of the existing header.
- skip - 不替换现有标头值。- skip - does not replace the existing header value.
- append - 将值追加到现有标头值。- append - appends the value to the existing header value.
- delete - 从请求中删除标头。- delete - removes the header from the request.

如果设置为 override,则登记多个同名的条目会导致根据所有条目(将多次列出)设置标头;结果中只会设置列出的值。When set to override enlisting multiple entries with the same name results in the header being set according to all entries (which will be listed multiple times); only listed values will be set in the result.
No overrideoverride

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

设置 HTTP 代理Set HTTP proxy

proxy 策略允许通过 HTTP 代理将转发的请求路由到后端。The proxy policy allows you to route requests forwarded to backends via an HTTP proxy. 网关和代理之间仅支持 HTTP(而不是 HTTPS)。Only HTTP (not HTTPS) is supported between the gateway and the proxy. 仅限基本和 NTLM 身份验证。Basic and NTLM authentication only.

策略语句Policy statement

<proxy url="http://hostname-or-ip:port" username="username" password="password" />

示例Example

请注意使用属性作为用户名和密码的值,以避免将敏感信息存储在策略文档中。Note the use of properties as values of the username and password to avoid storing sensitive information in the policy document.

<proxy url="http://192.168.1.1:8080" username={{username}} password={{password}} />

元素Elements

元素Element 描述Description 必须Required
proxyproxy Root 元素Root element Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
url="string"url="string" http://host:port 形式的代理 URL。Proxy URL in the form of http://host:port. Yes 空值N/A
username="string"username="string" 要用于向代理进行身份验证的用户名。Username to be used for authentication with the proxy. No 空值N/A
password="string"password="string" 要用于向代理进行身份验证的密码。Password to be used for authentication with the proxy. No 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound

  • 策略范围: 所有范围Policy scopes: all scopes

设置请求方法Set request method

set-method 策略用于更改请求的 HTTP 请求方法。The set-method policy allows you to change the HTTP request method for a request.

策略语句Policy statement

<set-method>METHOD</set-method>

示例Example

以下示例策略使用 set-method 策略,以示例方式演示了在 HTTP 响应代码大于或等于 500 的情况下,如何将消息发送到 Slack 聊天室。This sample policy that uses the set-method policy shows an example of sending a message to a Slack chat room if the HTTP response code is greater than or equal to 500. 有关此示例的详细信息,请参阅通过 Azure API 管理服务使用外部服务For more information on this sample, see Using external services from the Azure API Management service.

<choose>
    <when condition="@(context.Response.StatusCode >= 500)">
      <send-one-way-request mode="new">
        <set-url>https://hooks.slack.com/services/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</set-url>
        <set-method>POST</set-method>
        <set-body>@{
                return new JObject(
                        new JProperty("username","APIM Alert"),
                        new JProperty("icon_emoji", ":ghost:"),
                        new JProperty("text", String.Format("{0} {1}\nHost: {2}\n{3} {4}\n User: {5}",
                                                context.Request.Method,
                                                context.Request.Url.Path + context.Request.Url.QueryString,
                                                context.Request.Url.Host,
                                                context.Response.StatusCode,
                                                context.Response.StatusReason,
                                                context.User.Email
                                                ))
                        ).ToString();
            }</set-body>
      </send-one-way-request>
    </when>
</choose>

元素Elements

元素Element 描述Description 必须Required
set-methodset-method 根元素。Root element. 此元素的值指定 HTTP 方法。The value of the element specifies the HTTP method. Yes

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、错误时Policy sections: inbound, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

设置状态代码Set status code

set-status 策略将 HTTP 状态代码设置为指定的值。The set-status policy sets the HTTP status code to the specified value.

策略语句Policy statement

<set-status code="" reason=""/>

示例Example

以下示例演示如何在授权令牌无效的情况下返回 401 响应。This example shows how to return a 401 response if the authorization token is invalid. 有关详细信息,请参阅通过 Azure API 管理服务使用外部服务For more information, see Using external services from the Azure API Management service

<choose>
  <when condition="@((bool)((IResponse)context.Variables["tokenstate"]).Body.As<JObject>()["active"] == false)">
    <return-response response-variable-name="existing response variable">
      <set-status code="401" reason="Unauthorized" />
      <set-header name="WWW-Authenticate" exists-action="override">
        <value>Bearer error="invalid_token"</value>
      </set-header>
    </return-response>
  </when>
</choose>

元素Elements

元素Element 描述Description 必须Required
set-statusset-status 根元素。Root element. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
code="整数"code="integer" 要返回的 HTTP 状态代码。The HTTP status code to return. Yes 空值N/A
reason="字符串"reason="string" 说明返回状态代码的原因。A description of the reason for returning the status code. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 出站、后端、错误时Policy sections: outbound, backend, on-error
  • 策略范围: 所有范围Policy scopes: all scopes

设置变量Set variable

set-variable 策略声明上下文变量,并为其分配通过表达式或字符串文本指定的值。The set-variable policy declares a context variable and assigns it a value specified via an expression or a string literal. 如果表达式包含文本,则会将其转换为字符串,值的类型将为 System.Stringif the expression contains a literal it will be converted to a string and the type of the value will be System.String.

策略语句Policy statement

<set-variable name="variable name" value="Expression | String literal" />

示例Example

以下示例演示入站节中的 set-variable 策略。The following example demonstrates a set variable policy in the inbound section. 此 set-variable 策略用于创建 isMobile 布尔上下文变量,该变量在 User-Agent 请求标头包含文本 iPadiPhone 的情况下设置为 true。This set variable policy creates an isMobile Boolean context variable that is set to true if the User-Agent request header contains the text iPad or iPhone.

<set-variable name="IsMobile" value="@(context.Request.Headers["User-Agent"].Contains("iPad") || context.Request.Headers["User-Agent"].Contains("iPhone"))" />

元素Elements

元素Element 描述Description 必须Required
set-variableset-variable 根元素。Root element. Yes

属性Attributes

属性Attribute 描述Description 必需Required
namename 变量的名称。The name of the variable. Yes
valuevalue 变量的值,The value of the variable. 可以是表达式或文本值。This can be an expression or a literal value. Yes

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error
  • 策略范围: 所有范围Policy scopes: all scopes

允许的类型Allowed types

set-variable 策略中使用的表达式必须返回以下基本类型之一。Expressions used in the set-variable policy must return one of the following basic types.

  • System.BooleanSystem.Boolean
  • System.SByteSystem.SByte
  • System.ByteSystem.Byte
  • System.UInt16System.UInt16
  • System.UInt32System.UInt32
  • System.UInt64System.UInt64
  • System.Int16System.Int16
  • System.Int32System.Int32
  • System.Int64System.Int64
  • System.DecimalSystem.Decimal
  • System.SingleSystem.Single
  • System.DoubleSystem.Double
  • System.GuidSystem.Guid
  • System.StringSystem.String
  • System.CharSystem.Char
  • System.DateTimeSystem.DateTime
  • System.TimeSpanSystem.TimeSpan
  • System.Byte?System.Byte?
  • System.UInt16?System.UInt16?
  • System.UInt32?System.UInt32?
  • System.UInt64?System.UInt64?
  • System.Int16?System.Int16?
  • System.Int32?System.Int32?
  • System.Int64?System.Int64?
  • System.Decimal?System.Decimal?
  • System.Single?System.Single?
  • System.Double?System.Double?
  • System.Guid?System.Guid?
  • System.String?System.String?
  • System.Char?System.Char?
  • System.DateTime?System.DateTime?

跟踪Trace

trace 策略将自定义跟踪添加到 API 检查器输出、Application Insights 遥测和/或资源日志。The trace policy adds a custom trace into the API Inspector output, Application Insights telemetries, and/or Resource Logs.

  • 触发跟踪时,策略将自定义跟踪添加到 API 检查器输出,即显示 Ocp-Apim-Trace 请求标头且将其设置为“true”,并显示 Ocp-Apim-Subscription-Key 请求标头,其中包含允许跟踪的有效密钥。The policy adds a custom trace to the API Inspector output when tracing is triggered, i.e. Ocp-Apim-Trace request header is present and set to true and Ocp-Apim-Subscription-Key request header is present and holds a valid key that allows tracing.
  • 当启用 Application Insights 集成且在策略中指定的 severity 级别等于或高于在诊断设置中指定的 verbosity 级别时,此策略在 Application Insights 中创建跟踪遥测。The policy creates a Trace telemetry in Application Insights, when Application Insights integration is enabled and the severity level specified in the policy is at or higher than the verbosity level specified in the diagnostic setting.
  • 当启用资源日志并且策略中指定的严重级别等于或高于诊断设置中指定的详细级别时,策略将在日志条目中添加属性。The policy adds a property in the log entry when Resource Logs is enabled and the severity level specified in the policy is at or higher than the verbosity level specified in the diagnostic setting.

策略语句Policy statement


<trace source="arbitrary string literal" severity="verbose|information|error">
    <message>String literal or expressions</message>
    <metadata name="string literal or expressions" value="string literal or expressions"/>
</trace>

示例Example

<trace source="PetStore API" severity="verbose">
    <message>@((string)context.Variables["clientConnectionID"])</message>
    <metadata name="Operation Name" value="New-Order"/>
</trace>

元素Elements

元素Element 描述Description 必须Required
tracetrace 根元素。Root element. Yes
messagemessage 要记录的字符串或表达式。A string or expression to be logged. Yes
metadatametadata 将自定义属性添加到 Application Insights 跟踪遥测。Adds a custom property to the Application Insights Trace telemetry. No

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
sourcesource 对跟踪查看器有意义的字符串文本,指定消息的源。String literal meaningful to the trace viewer and specifying the source of the message. Yes 空值N/A
severityseverity 指定跟踪的严重性级别。Specifies the severity level of the trace. 允许的值为 verboseinformationerror(从低到高)。Allowed values are verbose, information, error (from lowest to highest). No 详细Verbose
namename 属性的名称。Name of the property. Yes 空值N/A
valuevalue 属性的名称。Value of the property. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes .

  • 策略节: 入站、出站、后端、错误时Policy sections: inbound, outbound, backend, on-error

  • 策略范围: 所有范围Policy scopes: all scopes

等待Wait

wait 策略以并行方式执行其直接子策略,在完成之前会等待其直接子策略全部完成或其中一个完成。The wait policy executes its immediate child policies in parallel, and waits for either all or one of its immediate child policies to complete before it completes. 等待策略可以将发送请求从缓存中获取值控制流策略设置为其直接子策略。The wait policy can have as its immediate child policies Send request, Get value from cache, and Control flow policies.

策略语句Policy statement

<wait for="all|any">
  <!--Wait policy can contain send-request, cache-lookup-value,
        and choose policies as child elements -->
</wait>

示例Example

在以下示例中有两个 choose 策略,充当 wait 策略的直接子策略。In the following example there are two choose policies as immediate child policies of the wait policy. 这些 choose 策略都可以并行执行。Each of these choose policies executes in parallel. 每个 choose 策略都会尝试检索缓存的值。Each choose policy attempts to retrieve a cached value. 如果缓存未命中,则会调用后端服务来提供值。If there is a cache miss, a backend service is called to provide the value. 在此示例中,wait 策略在完成之前必须等待其所有直接子策略完成,因为 for 属性设置为 allIn this example the wait policy does not complete until all of its immediate child policies complete, because the for attribute is set to all. 在此示例中,上下文变量(execute-branch-onevalue-oneexecute-branch-twovalue-two)是在此示例策略范围外声明的。In this example the context variables (execute-branch-one, value-one, execute-branch-two, and value-two) are declared outside of the scope of this example policy.

<wait for="all">
  <choose>
    <when condition="@((bool)context.Variables["execute-branch-one="])">
      <cache-lookup-value key="key-one" variable-name="value-one" />
      <choose>
        <when condition="@(!context.Variables.ContainsKey("value-one="))">
          <send-request mode="new" response-variable-name="value-one">
            <set-url>https://backend-one</set-url>
            <set-method>GET</set-method>
          </send-request>
        </when>
      </choose>
    </when>
  </choose>
  <choose>
    <when condition="@((bool)context.Variables["execute-branch-two="])">
      <cache-lookup-value key="key-two" variable-name="value-two" />
      <choose>
        <when condition="@(!context.Variables.ContainsKey("value-two="))">
          <send-request mode="new" response-variable-name="value-two">
            <set-url>https://backend-two</set-url>
            <set-method>GET</set-method>
          </send-request>
        </when>
      </choose>
    </when>
  </choose>
</wait>

元素Elements

元素Element 描述Description 必须Required
waitwait 根元素。Root element. 可能只包含 send-requestcache-lookup-valuechoose 策略作为子元素。May contain as child elements only send-request, cache-lookup-value, and choose policies. Yes

属性Attributes

属性Attribute 描述Description 必须Required 默认Default
forfor 确定 wait 策略是等待所有直接子策略完成,还是只等待其中之一完成。Determines whether the wait policy waits for all immediate child policies to be completed or just one. 允许值包括:Allowed values are:

- all - 等待所有直接子策略完成- all - wait for all immediate child policies to complete
- any - 等待任一直接子策略完成。- any - wait for any immediate child policy to complete. 第一个直接子策略完成后,wait 策略即告完成,同时会终止执行任何其他直接子策略。Once the first immediate child policy has completed, the wait policy completes and execution of any other immediate child policies is terminated.
No allall

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站、后端Policy sections: inbound, outbound, backend
  • 策略范围: 所有范围Policy scopes: all scopes

后续步骤Next steps

有关如何使用策略的详细信息,请参阅:For more information working with policies, see: