【API Management】使用 APIM Inbound Policy 来修改Content‐Type Header的值

发布时间 2023-09-07 20:34:14作者: 路边两盏灯

问题描述

在使用APIM提供API服务管理的场景中,遇见了客户端请求时候发送的请求Header中的Content-Type不满足后台服务器的要求,但是在客户端要求客户修改代码难度较高。

所以面对这样的情况,是否在APIM端修改为对请求的Content-Type进行覆写呢? 

 

问题解答

可以的。

APIM支持通过设置策略(Policy)来改变请求的Header,使用的策略语句时 set-header, 可以实现覆写,追加,删除等操作。

在本案例中,需要使用的 set-header策略如下:

<inbound> 
        <base />
        <set-header name="Content-Type" exists-action="override">
            <value>application/json; charset=utf-8</value>
        </set-header>
</inbound>

注意:因为时需要把请求传递到后端API服务器,所以需要在APIM的入站(Inbound)策略中设置,如果设置在出站(Outbound)策略中,它修改的不是请求的Header,而变成了APIM返回给客户端调用的Response Header。

 

参考资料

APIM Set-Header策略:​​https://docs.azure.cn/zh-cn/api-management/set-header-policy​​ 

The set-header policy assigns a value to an existing HTTP response and/or request header or adds a new response and/or request header.

Use the policy to insert a list of HTTP headers into an HTTP message. When placed in an inbound pipeline, this policy sets the HTTP headers for the request being passed to the target service. When placed in an outbound pipeline, this policy sets the HTTP headers for the response being sent to the gateway’s client.