【APIM】分享APIM策略用于检查请求实体(Request Body Size)大于50MB直接返回提示信息

问题描述

使用APIM服务,当遇见上传文件的请求时,需要考虑大文件对APIM性能的影响。

所以,是否可以使用APIM策略来监测请求body大小,如果超过50MB,就返回413 Payload too Large呢?

问题解答

当然可以。实现思路如下:

1: 在API的Policy中,在Inbound中获取请求的Size(context.Request.Headers["Content-Length"][0])并保存为一个参数bodySize

2: 使用choose 语句来判断bodySize小于 50MB ( 50 * 1024 * 1024 = 52428800 bytes), 小于则继续。

3: 如果大于了50MB,就使用 return-response 返回413并添加提示信息

示例策略如下:

<policies>
    <inbound>
        <base />
        <set-variable name="bodySize" value="@(context.Request.Headers["Content-Length"][0])" />
        <choose>
            <when condition="@(int.Parse(context.Variables.GetValueOrDefault<string>("bodySize"))<52428800)">
                <!--let it pass through by doing nothing-->
            </when>
            <otherwise>
                <return-response>
                    <set-status code="413" reason="Payload too large" />
                    <set-body>@{
                       return "Maximum allowed size for the requests is 50 MB. This request has size of "+ context.Variables.GetValueOrDefault<string>("bodySize") +" bytes";
                    }</set-body>
                </return-response>
            </otherwise>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

测试结果如下:


image.png

参考资料

APIM Policy 设置变量 : https://docs.azure.cn/zh-cn/api-management/set-variable-policy

APIM Policy 返回响应 : https://docs.azure.cn/zh-cn/api-management/return-response-policy

APIM Policy 控制流 : https://docs.azure.cn/zh-cn/api-management/choose-policy

How to prevent large file POST requests using Azure APIM? https://stackoverflow.com/questions/60448273/how-to-prevent-large-file-post-requests-using-azure-apim

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容