在Azure API Management中,如果某些简单验证失败,是否可以跳过后端调用?我需要这个,因为在这种情况下对后端服务的每次调用都使用了客户端配额的一部分,如果我们知道请求会失败,这是不可取的。
采用以下示例,其中网址模板为/MyOperation/{MyParameter}
:
<inbound>
部分首先检查{MyParameter}
是否为数字,然后重写URI。<outbound>
部分会检查{MyParameter}
是否有效,如果没有,则会向客户返回一些自定义文字。以下是示例政策 -
<policies>
<inbound>
<set-variable name="isValidMyParameter" value="@{
Match match = Regex.Match(context.Request.MatchedParameters["MyParameter"], "^[0-9]*$");
return ( match.Value.ToString() != "" ) ? true : false;
}" />
<rewrite-uri template="@("/Path/To/Application/" + ""+context.Request.MatchedParameters["MyParameter"])" />
</inbound>
<outbound>
<choose>
<when condition=""@(!Convert.ToBoolean(context.Variables["isValidMyParameter"]))">
<set-status code="400" reason="Bad Request" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{ "statusCode": 400, "message": "Invalid 'MyParameter'." }</set-body>
</when>
</outbound>
</policies>
虽然有效,即使{MyParameter}
无效(比如客户端已通过“asdf”),也会对后端服务发出请求。如上所述,这是不可取的,因为它会占用客户端配额。
我考虑使用<choose>
并检查isValidMyParameter
的值,但问题是仍然发出了对后端服务的请求,只是没有重写的URI。这再次进入客户配额。
是否可以跳过保单的<backend>
部分并直接回到客户端?
答案 0 :(得分:2)
移动选择并在入站正文中添加退货响应政策。这将导致客户端立即响应跳过后端请求。
<inbound>
<set-variable name="isValidMyParameter" value="@{
Match match = Regex.Match(context.Request.MatchedParameters["MyParameter"], "^[0-9]*$");
return ( match.Value.ToString() != "" ) ? true : false;
}" />
<choose>
<when condition="@(!Convert.ToBoolean(context.Variables["isValidMyParameter"]))">
<return-response>
<set-status code="400" reason="Bad Request" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{ "statusCode": 400, "message": "Invalid 'MyParameter'." }</set-body>
</return-response>
</when>
</choose>
<rewrite-uri template="@("/Path/To/Application/" + ""+context.Request.MatchedParameters["MyParameter"])" />
</inbound>
答案 1 :(得分:1)
了解回复政策。它允许您立即停止请求处理并将响应返回给客户端。