将请求上下文信息转发到后端服务Send request context information to the backend service

本文介绍 Azure API 管理策略示例,该示例演示如何将请求上下文信息发送到后端服务。This article shows an Azure API management policy sample that demonstrates how to send request context information to the backend service. 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。To set or edit a policy code, follow the steps described in Set or edit a policy. 若要查看其他示例,请参阅策略示例To see other examples, see policy samples.

策略Policy

将代码粘贴到“入站”块中。Paste the code into the inbound block.

<!-- The policies described in this file show how to send some context information to the backend service for logging or processing. -->

<!-- Copy these snippets into the inbound element -->

<policies>
  <inbound>
    <base />
      <!-- Forward the name of the product associated with the subscription key in the request to the backend service. -->
      <set-query-parameter name="x-product-name" exists-action="override">
        <value>@(context.Product.Name)</value>
      </set-query-parameter>

      <!-- Forward the user id associated with the subscription key in the request as well as the region where the proxy processing the request is hosted. -->
      <set-header name="x-request-context-data" exists-action="override">
        <value>@(context.User.Id)</value>
        <value>@(context.Deployment.Region)</value>
      </set-header>    
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>

后续步骤Next steps

了解有关 APIM 策略的详细信息:Learn more about APIM policies: