基于请求的正文大小路由请求Route the request based on the size of its body

本文介绍 Azure API 管理策略示例,该示例演示如何基于请求的正文大小路由请求。This article shows an Azure API management policy sample that demonstrates how to route requests based on the size of their bodies. 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。To set or edit a policy code, follow the steps described in Set or edit a policy. 若要查看其他示例,请参阅策略示例To see other examples, see policy samples.

策略Policy

将代码粘贴到“入站”块中。Paste the code into the inbound block.

<!-- The policy defined in this file demonstrates how to route requests based on the size of the message body. -->
<!-- Content-Length header contains the size of the message body. -->

<!--  256 KB, a limitation on message size in the Azure Service Bus.  -->
<!-- The snippet checks if the message is smaller than 256000 bytes. If it's larger, request is routed somewhere else. -->

<!-- Copy the following snippet into the inbound section. -->

<policies>
    <inbound>
        <base/>
            <set-variable name="bodySize" value="@(context.Request.Headers["Content-Length"][0])"/>
            <choose>
                <when condition="@(int.Parse(context.Variables.GetValueOrDefault<string>("bodySize"))<256000)">
                    <!-- let it pass through by doing nothing -->
                </when>
                <otherwise>
                    <rewrite-uri template="{{alternate-path-and-query}}"/>
                    <set-backend-service base-url="{{alternate-host}}"/>
                </otherwise>
            </choose>

            <!-- In rare cases where Content-Length header is not present we'll have to read the body to get its length. -->
            <!--
            <choose>
                <when condition="@(context.Request.Body.As<string>(preserveContent: true).Length<256000)">

                </when>
                <otherwise>
                    <rewrite-uri template=""/>
                    <set-backend-service base-url=""/>
                </otherwise>
            </choose>
            -->
    </inbound>
    <backend>
        <base/>
    </backend>
    <outbound>
        <base/>
    </outbound>
    <on-error>
        <base/>
    </on-error>
</policies>

后续步骤Next steps

了解有关 APIM 策略的详细信息:Learn more about APIM policies: