API 管理转换策略API Management transformation 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.
转换策略Transformation policies
将 JSON 转换为 XML - 将请求或响应正文从 JSON 转换为 XML。Convert JSON to XML - Converts request or response body from JSON to XML.
将 XML 转换为 JSON - 将请求或响应正文从 XML 转换为 JSON。Convert XML to JSON - Converts request or response body from XML to JSON.
查找并替换正文中的字符串 - 查找请求或响应子字符串,并将其替换为不同的子字符串。Find and replace string in body - Finds a request or response substring and replaces it with a different substring.
在内容中屏蔽 URL - 重写(屏蔽)响应正文中的链接,使其通过网关指向等效的链接。Mask URLs in content - Re-writes (masks) links in the response body so that they point to the equivalent link via the gateway.
设置后端服务 - 更改传入请求的后端服务。Set backend service - Changes the backend service for an incoming request.
设置正文 - 设置传入和传出请求的消息正文。Set body - Sets the message body for incoming and outgoing requests.
设置 HTTP 标头 - 向现有的响应和/或请求标头赋值,或者添加新的响应和/或请求标头。Set HTTP header - Assigns a value to an existing response and/or request header or adds a new response and/or request header.
设置查询字符串参数 - 添加、删除请求查询字符串参数或替换其值。Set query string parameter - Adds, replaces value of, or deletes request query string parameter.
重写 URL - 将请求 URL 从其公用格式转换为 Web 服务所需的格式。Rewrite URL - Converts a request URL from its public form to the form expected by the web service.
使用 XSLT 转换 XML - 在请求或响应正文中将 XSL 转换应用到 XML。Transform XML using an XSLT - Applies an XSL transformation to XML in the request or response body.
将 JSON 转换为 XML Convert JSON to XML
json-to-xml
策略将请求或响应正文从 JSON 转换为 XML。The json-to-xml
policy converts a request or response body from JSON to XML.
策略语句Policy statement
<json-to-xml apply="always | content-type-json" consider-accept-header="true | false" parse-date="true | false"/>
示例Example
<policies>
<inbound>
<base />
</inbound>
<outbound>
<base />
<json-to-xml apply="always" consider-accept-header="false" parse-date="false"/>
</outbound>
</policies>
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
json-to-xmljson-to-xml | 根元素。Root element. | 是Yes |
属性Attributes
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
applyapply | 属性必须设置为以下值之一。The attribute must be set to one of the following values. - always - 始终应用转换。- always - always apply conversion. - content-type-json - 仅在响应的 Content-Type 标头指示存在 JSON 的情况下进行转换。- content-type-json - convert only if response Content-Type header indicates presence of JSON. |
是Yes | 空值N/A |
consider-accept-headerconsider-accept-header | 属性必须设置为以下值之一。The attribute must be set to one of the following values. - true - 如果在请求的 Accept 标头中请求了 XML,则应用转换。- true - apply conversion if XML is requested in request Accept header. - false - 始终应用转换。- false -always apply conversion. |
否No | 是true |
parse-dateparse-date | 设为 false 时,转换时则只是简单地复制日期值When set to false date values are simply copied during transformation |
否No | 是true |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、出站、错误时Policy sections: inbound, outbound, on-error
策略范围: 所有范围Policy scopes: all scopes
将 XML 转换为 JSONConvert XML to JSON
xml-to-json
策略将请求或响应正文从 XML 转换为 JSON。The xml-to-json
policy converts a request or response body from XML to JSON. 此策略可以用来根据仅用 XML 的后端 Web 服务来提升 API。This policy can be used to modernize APIs based on XML-only backend web services.
策略语句Policy statement
<xml-to-json kind="javascript-friendly | direct" apply="always | content-type-xml" consider-accept-header="true | false"/>
示例Example
<policies>
<inbound>
<base />
</inbound>
<outbound>
<base />
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />
</outbound>
</policies>
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
xml-to-jsonxml-to-json | 根元素。Root element. | 是Yes |
属性Attributes
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
kindkind | 属性必须设置为以下值之一。The attribute must be set to one of the following values. - javascript-friendly - 转换后的 JSON 具有 JavaScript 开发人员熟知的形式。- javascript-friendly - the converted JSON has a form friendly to JavaScript developers. - direct - 转换后的 JSON 反映了原始 XML 文档的结构。- direct - the converted JSON reflects the original XML document's structure. |
是Yes | 空值N/A |
applyapply | 属性必须设置为以下值之一。The attribute must be set to one of the following values. - always - 始终转换。- always - convert always. - content-type-xml - 仅在响应的 Content-Type 标头指示存在 XML 的情况下进行转换。- content-type-xml - convert only if response Content-Type header indicates presence of XML. |
是Yes | 空值N/A |
consider-accept-headerconsider-accept-header | 属性必须设置为以下值之一。The attribute must be set to one of the following values. - true - 如果在请求的 Accept 标头中请求了 JSON,则应用转换。- true - apply conversion if JSON is requested in request Accept header. - false - 始终应用转换。- false -always apply conversion. |
否No | 是true |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、出站、错误时Policy sections: inbound, outbound, on-error
策略范围: 所有范围Policy scopes: all scopes
在正文中查找并替换字符串Find and replace string in body
find-and-replace
策略查找请求或响应子字符串并将其替换为不同的子字符串。The find-and-replace
policy finds a request or response substring and replaces it with a different substring.
策略语句Policy statement
<find-and-replace from="what to replace" to="replacement" />
示例Example
<find-and-replace from="notebook" to="laptop" />
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
find-and-replacefind-and-replace | 根元素。Root element. | 是Yes |
属性Attributes
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
fromfrom | 要搜索的字符串。The string to search for. | 是Yes | 空值N/A |
toto | 替换字符串。The replacement string. 指定一个零长度的替换字符串,以便删除搜索字符串。Specify a zero length replacement string to remove the search string. | 是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
在内容中屏蔽 URLMask URLs in content
redirect-content-urls
策略重写(屏蔽)响应正文中的链接,使其通过网关指向等效的链接。The redirect-content-urls
policy re-writes (masks) links in the response body so that they point to the equivalent link via the gateway. 在出站节中用于重写响应正文链接,使之指向网关。Use in the outbound section to re-write response body links to make them point to the gateway. 在入站节中使用,以便获得相反的效果。Use in the inbound section for an opposite effect.
备注
此策略不更改任何标头值,例如 Location
标头值。This policy does not change any header values such as Location
headers. 若要更改标头值,请使用 set-header 策略。To change header values, use the set-header policy.
策略语句Policy statement
<redirect-content-urls />
示例Example
<redirect-content-urls />
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
redirect-content-urlsredirect-content-urls | 根元素。Root element. | 是Yes |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、出站Policy sections: inbound, outbound
策略范围: 所有范围Policy scopes: all scopes
设置后端服务Set backend service
使用 set-backend-service
策略将传入请求重定向到一个后端,此后端不同于在 API 设置中为该操作指定的后端。Use the set-backend-service
policy to redirect an incoming request to a different backend than the one specified in the API settings for that operation. 此策略将传入请求的后端服务基 URL 更改为在策略中指定的基 URL。This policy changes the backend service base URL of the incoming request to the one specified in the policy.
策略语句Policy statement
<set-backend-service base-url="base URL of the backend service" />
或or
<set-backend-service backend-id="identifier of the backend entity specifying base URL of the backend service" />
备注
后端实体可以通过管理 API 和PowerShell 进行管理。Backend entities can be managed via management API and PowerShell.
示例Example
<policies>
<inbound>
<choose>
<when condition="@(context.Request.Url.Query.GetValueOrDefault("version") == "2013-05")">
<set-backend-service base-url="http://contoso.com/api/8.2/" />
</when>
<when condition="@(context.Request.Url.Query.GetValueOrDefault("version") == "2014-03")">
<set-backend-service base-url="http://contoso.com/api/9.1/" />
</when>
</choose>
<base />
</inbound>
<outbound>
<base />
</outbound>
</policies>
在此示例中,所设置的后端服务策略根据查询字符串中传递的版本值将请求路由到一个后端服务,该服务不同于在 API 中指定的服务。In this example the set backend service policy routes requests based on the version value passed in the query string to a different backend service than the one specified in the API.
后端服务基 URL 最初派生自 API 设置。Initially the backend service base URL is derived from the API settings. 因此,请求 URL https://contoso.azure-api.net/api/partners/15?version=2013-05&subscription-key=abcdef
变为 http://contoso.com/api/10.4/partners/15?version=2013-05&subscription-key=abcdef
,其中 http://contoso.com/api/10.4/
是在 API 设置中指定的后端服务 URL。So the request URL https://contoso.azure-api.net/api/partners/15?version=2013-05&subscription-key=abcdef
becomes http://contoso.com/api/10.4/partners/15?version=2013-05&subscription-key=abcdef
where http://contoso.com/api/10.4/
is the backend service URL specified in the API settings.
应用 <choose> 策略语句时,后端服务基 URL 可能会再次更改为 http://contoso.com/api/8.2
或 http://contoso.com/api/9.1
,具体取决于版本请求查询参数的值。When the <choose> policy statement is applied the backend service base URL may change again either to http://contoso.com/api/8.2
or http://contoso.com/api/9.1
, depending on the value of the version request query parameter. 例如,如果值为 "2013-15"
,最终请求 URL 将变为 http://contoso.com/api/8.2/partners/15?version=2013-05&subscription-key=abcdef
。For example, if the value is "2013-15"
the final request URL becomes http://contoso.com/api/8.2/partners/15?version=2013-05&subscription-key=abcdef
.
如果需要进一步转换请求,可使用其他转换策略。If further transformation of the request is desired, other Transformation policies can be used. 例如,在将请求路由到特定于版本的后端以后,要删除版本查询参数,可以使用设置查询字符串参数策略删除现在的冗余版本属性。For example, to remove the version query parameter now that the request is being routed to a version specific backend, the Set query string parameter policy can be used to remove the now redundant version attribute.
示例Example
<policies>
<inbound>
<set-backend-service backend-id="my-sf-service" sf-partition-key="@(context.Request.Url.Query.GetValueOrDefault("userId","")" sf-replica-type="primary" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
在此示例中,策略使用 userId 查询字符串作为分区键并使用该分区的主要副本,将请求路由到 Service Fabric 后端。In this example the policy routes the request to a service fabric backend, using the userId query string as the partition key and using the primary replica of the partition.
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
set-backend-serviceset-backend-service | 根元素。Root element. | 是Yes |
属性Attributes
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
base-urlbase-url | 新的后端服务基 URL。New backend service base URL. | 必须存在 base-url 或 backend-id 中的一个。One of base-url or backend-id must be present. |
空值N/A |
backend-idbackend-id | 要路由到的后端标识符。Identifier of the backend to route to. (后端实体通过 API 和 PowerShell 进行管理。)(Backend entities are managed via API and PowerShell.) | 必须存在 base-url 或 backend-id 中的一个。One of base-url or backend-id must be present. |
空值N/A |
sf-partition-keysf-partition-key | 只有在后端为 Service Fabric 服务且使用“backend-id”指定时才适用。Only applicable when the backend is a Service Fabric service and is specified using 'backend-id'. 用于从名称解析服务中解析特定分区。Used to resolve a specific partition from the name resolution service. | 否No | 空值N/A |
sf-replica-typesf-replica-type | 只有在后端为 Service Fabric 服务且使用“backend-id”指定时才适用。Only applicable when the backend is a Service Fabric service and is specified using 'backend-id'. 控制请求是否应转到分区的主要副本或次要副本。Controls if the request should go to the primary or secondary replica of a partition. | 否No | 空值N/A |
sf-resolve-conditionsf-resolve-condition | 只有在后端为 Service Fabric 服务时才适用。Only applicable when the backend is a Service Fabric service. 确定对 Service Fabric 后端的调用是否针对新解析重复进行的条件。Condition identifying if the call to Service Fabric backend has to be repeated with new resolution. | 否No | 空值N/A |
sf-service-instance-namesf-service-instance-name | 只有在后端为 Service Fabric 服务时才适用。Only applicable when the backend is a Service Fabric service. 允许在运行时更改服务实例。Allows to change service instances at runtime. | 否No | 空值N/A |
sf-listener-namesf-listener-name | 只有在后端为 Service Fabric 服务且使用“backend-id”指定时才适用。Only applicable when the backend is a Service Fabric service and is specified using ‘backend-id’. 使用 Service Fabric Reliable Services 可在服务中创建多个侦听器。Service Fabric Reliable Services allows you to create multiple listeners in a service. 当后端可靠服务具有多个侦听器时,此属性用于选择特定侦听器。This attribute is used to select a specific listener when a backend Reliable Service has more than one listener. 如果未指定此属性,API 管理将尝试使用没有名称的侦听器。If this attribute is not specified, API Management will attempt to use a listener without a name. 没有名称的侦听器对于只有一个侦听器的 Reliable Services 来说是非常典型的。A listener without a name is typical for Reliable Services that have only one listener. | 否No | 空值N/A |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、后端Policy sections: inbound, backend
策略范围: 所有范围Policy scopes: all scopes
设置正文Set body
使用 set-body
策略设置传入和传出请求的消息正文。Use the set-body
policy to set the message body for incoming and outgoing requests. 可以使用 context.Request.Body
属性或 context.Response.Body
访问消息正文,具体取决于策略是在入站节中还是在出站节中。To access the message body you can use the context.Request.Body
property or the context.Response.Body
, depending on whether the policy is in the inbound or outbound section.
重要
请注意,默认情况下,当用户使用 context.Request.Body
或 context.Response.Body
访问消息正文时,原始的消息正文会丢失,必须将正文返回到表达式中,以便对其进行设置。Note that by default when you access the message body using context.Request.Body
or context.Response.Body
, the original message body is lost and must be set by returning the body back in the expression. 若要保留正文内容,请在访问消息时将 preserveContent
参数设置为 true
。To preserve the body content, set the preserveContent
parameter to true
when accessing the message. 如果 preserveContent
设置为 true
,而表达式返回了不同的正文,则会使用返回的正文。If preserveContent
is set to true
and a different body is returned by the expression, the returned body is used.
在使用 set-body
策略时,请注意以下事项。Please note the following considerations when using the set-body
policy.
- 若要使用
set-body
策略返回全新的或更新的正文,则不需将preserveContent
设置为true
,因为是在显式提供全新的正文内容。If you are using theset-body
policy to return a new or updated body you don't need to setpreserveContent
totrue
because you are explicitly supplying the new body contents.- 将响应的内容保留在入站管道中并不合理,因为尚无响应。Preserving the content of a response in the inbound pipeline doesn't make sense because there is no response yet.
- 将请求的内容保留在出站管道中并不合理,因为请求此时已发送到后端。Preserving the content of a request in the outbound pipeline doesn't make sense because the request has already been sent to the backend at this point.
- 如果在没有消息正文的情况下使用此策略(例如在入站 GET 中使用),则会引发异常。If this policy is used when there is no message body, for example in an inbound GET, an exception is thrown.
有关详细信息,请参阅上下文变量表中的 context.Request.Body
、context.Response.Body
、IMessage
部分。For more information, see the context.Request.Body
, context.Response.Body
, and the IMessage
sections in the Context variable table.
策略语句Policy statement
<set-body>new body value as text</set-body>
示例Examples
文字文本示例Literal text example
<set-body>Hello world!</set-body>
示例:访问字符串形式的正文。Example accessing the body as a string. 请注意,我们会保留原始请求正文,以便稍后可以在管道中进行访问。Note that we are preserving the original request body so that we can access it later in the pipeline.
<set-body>
@{
string inBody = context.Request.Body.As<string>(preserveContent: true);
if (inBody[0] =='c') {
inBody[0] = 'm';
}
return inBody;
}
</set-body>
示例:访问 JObject 形式的正文。Example accessing the body as a JObject. 请注意,由于我们不保留原始请求正文,因此稍后在管道进行访问将产生异常。Note that since we are not reserving the original request body, accessing it later in the pipeline will result in an exception.
<set-body>
@{
JObject inBody = context.Request.Body.As<JObject>();
if (inBody.attribute == <tag>) {
inBody[0] = 'm';
}
return inBody.ToString();
}
</set-body>
根据产品筛选响应Filter response based on product
以下示例演示了如何进行内容筛选,方法是:在使用 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.
<!-- 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>
将 Liquid 模板用于设置正文Using Liquid templates with set body
可将 set-body
策略配置为使用 Liquid 模板语言以转换请求或响应正文。The set-body
policy can be configured to use the Liquid templating language to transform the body of a request or response. 如需完全重设消息格式,则此模板非常有用。This can be very effective if you need to completely reshape the format of your message.
重要
在“C# 模式”下配置 set-body
策略中使用的 Liquid 的实现。The implementation of Liquid used in the set-body
policy is configured in 'C# mode'. 执行筛选之类的操作时这点尤为重要。This is particularly important when doing things such as filtering. 例如,使用日期筛选器需要使用 Pascal 大小写和 C# 日期格式,如:As an example, using a date filter requires the use of Pascal casing and C# date formatting e.g.:
{{body.foo.startDateTime| Date:"yyyyMMddTHH:mm:ddZ"}}{{body.foo.startDateTime| Date:"yyyyMMddTHH:mm:ddZ"}}
重要
为正确绑定到使用 Liquid 模板的 XML 正文,请使用 set-header
策略将 Content-Type 设置为 application/xml、text/xml 或任何以 +xml 结尾的类型;对于 JSON 正文,其必须是 application/json、text/json 或任何以 +json 结尾的类型。In order to correctly bind to an XML body using the Liquid template, use a set-header
policy to set Content-Type to either application/xml, text/xml (or any type ending with +xml); for a JSON body, it must be application/json, text/json (or any type ending with +json).
使用 Liquid 模板将 JSON 转换为 SOAPConvert JSON to SOAP using a Liquid template
<set-body template="liquid">
<soap:Envelope xmlns="http://tempuri.org/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetOpenOrders>
<cust>{{body.getOpenOrders.cust}}</cust>
</GetOpenOrders>
</soap:Body>
</soap:Envelope>
</set-body>
使用 Liquid 模板转换 JSONTransform JSON using a Liquid template
{
"order": {
"id": "{{body.customer.purchase.identifier}}",
"summary": "{{body.customer.purchase.orderShortDesc}}"
}
}
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
set-bodyset-body | 根元素。Root element. 包含正文文本,或者包含会返回正文的表达式。Contains the body text or an expressions that returns a body. | 是Yes |
属性Properties
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
templatetemplate | 用于更改设置正文策略运行的模板模式。Used to change the templating mode that the set body policy will run in. 目前唯一支持的值是:Currently the only supported value is: - liquid - 设置正文策略会使用 liquid 模板引擎- liquid - the set body policy will use the liquid templating engine |
否No |
对于访问请求和响应信息,Liquid 模板可绑定到具有以下属性的上下文对象:For accessing information about the request and response, the Liquid template can bind to a context object with the following properties:
context. Request. Url Method OriginalMethod OriginalUrl IpAddress MatchedParameters HasBody ClientCertificates Headers Response. StatusCode Method Headers Url. Scheme Host Port Path Query QueryString ToUri ToString OriginalUrl. Scheme Host Port Path Query QueryString ToUri ToString
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、出站、后端Policy sections: inbound, outbound, backend
策略范围: 所有范围Policy scopes: all scopes
设置 HTTP 标头Set HTTP header
set-header
策略向现有的响应和/或请求标头赋值,或者添加新的响应和/或请求标头。The set-header
policy assigns a value to an existing response and/or request header or adds a new response and/or request header.
在 HTTP 消息中插入 HTTP 标头列表。Inserts a list of HTTP headers into an HTTP message. 将此策略放到入站管道中后,它将为传递给目标服务的请求设置 HTTP 标头。When placed in an inbound pipeline, this policy sets the HTTP headers for the request being passed to the target service. 将此策略放到出站管道中后,它将为发送到网关客户端的响应设置 HTTP 标头。When placed in an outbound pipeline, this policy sets the HTTP headers for the response being sent to the gateway’s client.
策略语句Policy statement
<set-header name="header name" exists-action="override | skip | append | delete">
<value>value</value> <!--for multiple headers with the same name add additional value elements-->
</set-header>
示例Examples
示例 - 添加标头,替代现有标头Example - adding header, override existing
<set-header name="some header name" exists-action="override">
<value>20</value>
</set-header>
示例 - 删除标头Example - removing header
<set-header name="some header name" exists-action="delete" />
将上下文信息转发到后端服务Forward context information to the backend service
此示例演示了如何在 API 级别应用策略,以便将上下文信息提供给后端服务。This example shows how to apply policy at the API level to supply context information to the backend service.
<!-- Copy this snippet into the inbound element to forward some context information, user id and the region the gateway is hosted in, to the backend service for logging or evaluation -->
<set-header name="x-request-context-data" exists-action="override">
<value>@(context.User.Id)</value>
<value>@(context.Deployment.Region)</value>
</set-header>
有关详细信息,请参阅策略表达式和上下文变量。For more information, see Policy expressions and Context variable.
备注
可以将一个标头的多个值连接成一个 CSV 字符串,例如:headerName: value1,value2,value3
Multiple values of a header are concatenated to a CSV string, for example: headerName: value1,value2,value3
例外包括标准化标头,其值:Exceptions include standardized headers, which values:
- 可能包含逗号(
User-Agent
、WWW-Authenticate
、Proxy-Authenticate
),may contain commas (User-Agent
,WWW-Authenticate
,Proxy-Authenticate
), - 可能包含日期(
Cookie
、Set-Cookie
、Warning
),may contain date (Cookie
,Set-Cookie
,Warning
), - 包含日期(
Date
、Expires
、If-Modified-Since
、If-Unmodified-Since
、Last-Modified
、Retry-After
)。contain date (Date
,Expires
,If-Modified-Since
,If-Unmodified-Since
,Last-Modified
,Retry-After
).
如果出现这些例外,则多个标头值不会连接成一个字符串,而是作为单独的标头传递,例如:User-Agent: value1
User-Agent: value2
User-Agent: value3
In case of those exceptions, multiple header values will not be concatenated into one string and will be passed as separate headers, for example: User-Agent: value1
User-Agent: value2
User-Agent: value3
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
set-headerset-header | 根元素。Root element. | 是Yes |
valuevalue | 指定要设置的标头的值。Specifies the value of the header to be set. 如需多个标头使用同一名称,可添加更多的 value 元素。For multiple headers with the same name add additional value elements. |
否No |
属性Properties
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
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 |
namename | 指定要设置的标头的名称。Specifies name of the header to be set. | 是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
设置查询字符串参数Set query string parameter
set-query-parameter
策略添加、删除请求查询字符串参数或替换其值。The set-query-parameter
policy adds, replaces value of, or deletes request query string parameter. 可用于传递后端服务所需的查询参数,这些参数是可选的或者永远不能出现在请求中。Can be used to pass query parameters expected by the backend service which are optional or never present in the request.
策略语句Policy statement
<set-query-parameter name="param name" exists-action="override | skip | append | delete">
<value>value</value> <!--for multiple parameters with the same name add additional value elements-->
</set-query-parameter>
示例Example
<set-query-parameter name="api-key" exists-action="skip">
<value>12345678901</value>
</set-query-parameter>
将上下文信息转发到后端服务Forward context information to the backend service
此示例演示了如何在 API 级别应用策略,以便将上下文信息提供给后端服务。This example shows how to apply policy at the API level to supply context information to the backend service.
<!-- Copy this snippet into the inbound element to forward a piece of context, product name in this example, to the backend service for logging or evaluation -->
<set-query-parameter name="x-product-name" exists-action="override">
<value>@(context.Product.Name)</value>
</set-query-parameter>
有关详细信息,请参阅策略表达式和上下文变量。For more information, see Policy expressions and Context variable.
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
set-query-parameterset-query-parameter | 根元素。Root element. | 是Yes |
valuevalue | 指定要设置的查询参数的值。Specifies the value of the query parameter to be set. 如需多个查询参数使用同一名称,可添加更多的 value 元素。For multiple query parameters with the same name add additional value elements. |
是Yes |
属性Properties
名称Name | 说明Description | 必须Required | 默认Default |
---|---|---|---|
exists-actionexists-action | 指定当查询参数已指定时要执行的操作。Specifies what action to take when the query parameter is already specified. 此属性必须具有下列值之一。This attribute must have one of the following values. - override - 替换现有参数的值。- override - replaces the value of the existing parameter. - skip - 不替换现有查询参数值。- skip - does not replace the existing query parameter value. - append - 将值追加到现有查询参数值。- append - appends the value to the existing query parameter value. - delete - 从请求中删除查询参数。- delete - removes the query parameter from the request. 如果设置为 override ,则登记多个同名的条目会导致根据所有条目(将多次列出)设置查询参数;结果中只会设置列出的值。When set to override enlisting multiple entries with the same name results in the query parameter being set according to all entries (which will be listed multiple times); only listed values will be set in the result. |
否No | overrideoverride |
namename | 指定要设置的查询参数的名称。Specifies name of the query parameter to be set. | 是Yes | 空值N/A |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、后端Policy sections: inbound, backend
策略范围: 所有范围Policy scopes: all scopes
重写 URLRewrite URL
rewrite-uri
策略将请求 URL 从其公用格式转换为 Web 服务所需的格式,如以下示例所示。The rewrite-uri
policy converts a request URL from its public form to the form expected by the web service, as shown in the following example.
公共 URL -
http://api.example.com/storenumber/ordernumber
Public URL -http://api.example.com/storenumber/ordernumber
请求 URL -
http://api.example.com/v2/US/hardware/storenumber&ordernumber?City&State
Request URL -http://api.example.com/v2/US/hardware/storenumber&ordernumber?City&State
如果要将用户和/或浏览器友好的 URL 转换成 Web 服务所需的 URL 格式,则可使用此策略。This policy can be used when a human and/or browser-friendly URL should be transformed into the URL format expected by the web service. 应用此策略的前提是公开备用的 URL 格式,例如简洁 URL、RESTful URL、用户友好的 URL 或 SEO 友好的 URL。这些 URL 是纯结构化 URL,不包含查询字符串,只包含资源的路径(在方案和颁发机构的后面)。This policy only needs to be applied when exposing an alternative URL format, such as clean URLs, RESTful URLs, user-friendly URLs or SEO-friendly URLs that are purely structural URLs that do not contain a query string and instead contain only the path of the resource (after the scheme and the authority). 通常会出于美观、可用性或搜索引擎优化 (SEO) 目的使用这种 URL。This is often done for aesthetic, usability, or search engine optimization (SEO) purposes.
备注
只能使用此策略添加查询字符串参数。You can only add query string parameters using the policy. 不能在重写 URL 中添加额外的模板路径参数。You cannot add extra template path parameters in the rewrite URL.
策略语句Policy statement
<rewrite-uri template="uri template" copy-unmatched-params="true | false" />
示例Example
<policies>
<inbound>
<base />
<rewrite-uri template="/v2/US/hardware/{storenumber}&{ordernumber}?City=city&State=state" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
<!-- Assuming incoming request is /get?a=b&c=d and operation template is set to /get?a={b} -->
<policies>
<inbound>
<base />
<rewrite-uri template="/put" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
<!-- Resulting URL will be /put?c=d -->
<!-- Assuming incoming request is /get?a=b&c=d and operation template is set to /get?a={b} -->
<policies>
<inbound>
<base />
<rewrite-uri template="/put" copy-unmatched-params="false" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
<!-- Resulting URL will be /put -->
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
rewrite-urirewrite-uri | 根元素。Root element. | 是Yes |
属性Attributes
属性Attribute | 说明Description | 必须Required | 默认Default |
---|---|---|---|
templatetemplate | 包含任何查询字符串参数的实际 Web 服务 URL。The actual web service URL with any query string parameters. 使用表达式时,整个值必须是一个表达式。When using expressions, the whole value must be an expression. | 是Yes | 空值N/A |
copy-unmatched-paramscopy-unmatched-params | 指定是否将原始 URL 模板中不存在的传入请求中的查询参数添加到重新编写模板定义的 URLSpecifies whether query parameters in the incoming request not present in the original URL template are added to the URL defined by the re-write template | 否No | 是true |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站Policy sections: inbound
策略范围: 所有范围Policy scopes: all scopes
使用 XSLT 转换 XMLTransform XML using an XSLT
Transform XML using an XSLT
策略在请求或响应正文中将 XSL 转换应用到 XML。The Transform XML using an XSLT
policy applies an XSL transformation to XML in the request or response body.
策略语句Policy statement
<xsl-transform>
<parameter name="User-Agent">@(context.Request.Headers.GetValueOrDefault("User-Agent","non-specified"))</parameter>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:param name="User-Agent" />
<xsl:template match="* | @* | node()">
<xsl:copy>
<xsl:if test="self::* and not(parent::*)">
<xsl:attribute name="User-Agent">
<xsl:value-of select="$User-Agent" />
</xsl:attribute>
</xsl:if>
<xsl:apply-templates select="* | @* | node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</xsl-transform>
示例Example
<policies>
<inbound>
<base />
</inbound>
<outbound>
<base />
<xsl-transform>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" method="xml" indent="yes" />
<!-- Copy all nodes directly-->
<xsl:template match="node()| @*|*">
<xsl:copy>
<xsl:apply-templates select="@* | node()|*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</xsl-transform>
</outbound>
</policies>
元素Elements
名称Name | 说明Description | 必须Required |
---|---|---|
xsl-transformxsl-transform | 根元素。Root element. | 是Yes |
参数parameter | 用于定义在转换中使用的变量Used to define variables used in the transform | 否No |
xsl:stylesheetxsl:stylesheet | 根样式表元素。Root stylesheet element. 在其中定义的所有元素和属性都遵循标准的 XSLT 规范All elements and attributes defined within follow the standard XSLT specification | 是Yes |
使用情况Usage
此策略可在以下策略节和范围中使用。This policy can be used in the following policy sections and scopes.
策略节: 入站、出站Policy sections: inbound, outbound
策略范围: 所有范围Policy scopes: all scopes
后续步骤Next steps
有关详细信息,请参阅以下主题:For more information, see the following topics:
- API 管理中的策略Policies in API Management
- 策略参考,获取策略语句及其设置的完整列表Policy Reference for a full list of policy statements and their settings
- 策略示例Policy samples