如何在Azure API管理策略表达式中正确检查请求体是否为空?
问题描述
我尝试通过以下方式检查请求体是否为空:
<set-variable name="isBody" value="@{ bool rtn_result = false; if (context.Request.Body == null) { rtn_result = true; } return rtn_result;}" />
但rtn_result始终返回false。我查阅文档得知:
"context.Request Body: IMessageBody or null if request doesn't have a body."
请问我哪里出错了?正确的做法是什么?谢谢。
解决方案
你的问题在于:即使请求没有携带实际的请求体内容,context.Request.Body也可能不会返回null,而是一个空的IMessageBody实例,这就导致你的判断条件永远不成立,rtn_result始终为false。
正确的检查逻辑需要结合Exists属性以及请求体内容的实际情况来判断:
针对文本类型请求体
<set-variable name="isBodyEmpty" value="@{ bool isEmpty = true; if (context.Request.Body != null && context.Request.Body.Exists) { string bodyContent = context.Request.Body.As<string>(); isEmpty = string.IsNullOrEmpty(bodyContent); } return isEmpty; }" />
简洁写法
<set-variable name="isBodyEmpty" value="@{ return context.Request.Body == null || !context.Request.Body.Exists || string.IsNullOrEmpty(context.Request.Body.As<string>()); }" />
针对二进制类型请求体
如果请求体是二进制数据,需要调整为检查字节数组是否为空:
<set-variable name="isBodyEmpty" value="@{ bool isEmpty = true; if (context.Request.Body != null && context.Request.Body.Exists) { byte[] bodyBytes = context.Request.Body.As<byte[]>(); isEmpty = bodyBytes == null || bodyBytes.Length == 0; } return isEmpty; }" />
内容的提问来源于stack exchange,提问作者Benji99
相关产品推荐
相关产品推荐

