如何在调用后端之前在 Azure API 管理中添加自定义标头

问题描述

我有一个在 Azure 上公开的 Rest Api。曾经调用过的 Azure Api 在后端调用一个 WCF 服务。

首先,我需要将 JSON 请求转换为 XML。另外,要调用 SOAP 服务,我需要添加一个像这样的自定义标题:-

 <s:Header>
      <AuthHeader xmlns="http://abc.security.service">
         <UserID>UserID</UserID>
         <Token>Token</Token>
      </AuthHeader>
   </s:Header>

如何添加将请求转换为 XML 并注入自定义标头的“入站策略”?

任何想法或建议将不胜感激!

解决方法

有关此要求,请参阅我的 APIM 中的政策。

<policies>
    <inbound>
        <base />
        <json-to-xml apply="always" />
        <set-body>@{ 
            string inBody = context.Request.Body.As<string>();
            string requestBody = inBody.Replace("<Document>","").Replace("</Document>","");
            string header = "<s:Header><AuthHeader xmlns=\"http://abc.security.service\"><UserID>UserID</UserID><Token>Token</Token></AuthHeader></s:Header>";
            return header + requestBody; 
        }</set-body>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

请注意 header 中的转义字符,我们需要使用 \" 而不是 "