Azure API Manager中打印入站请求头策略失效问题排查
问题分析与解决
核心问题
你的策略里<set-body>的写法有误:把C#表达式用双引号直接包裹,导致APIM没有解析表达式逻辑,直接输出了字符串文本。另外<return-response>执行后会终止请求流程,后续的<mock-response>属于冗余配置,不会被执行。
修正后的策略
场景1:仅返回Host请求头
<policies> <inbound> <base /> <set-variable name="HostName" value="@{ string[] HostNameHeader; context.Request.Headers.TryGetValue("Host", out HostNameHeader); return HostNameHeader?[0] ?? "Host header not found"; }" /> <return-response> <set-status code="200" /> <set-body>@(context.Variables["HostName"])</set-body> <set-header name="Content-Type" exists-action="override"> <value>text/plain</value> </set-header> </return-response> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
场景2:返回所有入站请求头(符合你排查需求)
无需额外变量,直接序列化所有请求头输出:
<policies> <inbound> <base /> <return-response> <set-status code="200" /> <set-body>@(Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers))</set-body> <set-header name="Content-Type" exists-action="override"> <value>application/json</value> </set-header> </return-response> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
关键修改说明
- 移除
<set-body>中的双引号,用@(表达式)语法让APIM执行C#逻辑 - 删除冗余的
<mock-response>,避免无效配置 - 增加
Content-Type响应头,明确返回格式 - 对Host头取值增加空值判断,防止空引用异常
- 全量返回头时利用JsonConvert序列化,输出结构化的请求头信息
内容的提问来源于stack exchange,提问作者perpetual confusion
相关产品推荐
相关产品推荐

