【Azure APIM】APIM Policy是否可以阻止大于50MB文件的上传呢? - LuBu0505/My-Code GitHub Wiki
在使用 Azure API Management(APIM)时,如何防止客户端发送过大的 POST 请求?例如,如何阻止任何超过 50MB 的文件上传请求,以避免资源浪费或潜在的服务中断。
**可以的。**通过在 Azure APIM 中配置策略(Policy)来实现对请求体大小的限制。
具体做法如下:
1: 依赖 Content-Length 头部信息:通过检查请求头中的 Content-Length 值来判断请求体大小。
2: 使用 Inbound 策略进行判断:在 API 的 inbound 策略中添加如下逻辑:
- 判断请求是否为 POST。
- 获取 Content-Length 值。
- 如果请求体大小超过 50MB(即 52428800 字节),则返回 HTTP 状态码 413(Payload Too Large)。
示例策略代码如下:
<!-- - Policies are applied in the order they appear.
- Position <base/> inside a section to inherit policies from the outer scope.
- Comments within policies are not preserved. -->
<!-- Add policies as children to the <inbound>, <outbound>, <backend>, and <on-error> elements -->
<policies>
<inbound>
<base />
<choose>
<when condition="@(context.Request.Method == 'POST')">
<set-variable name="bodySize" value="@(context.Request.Headers['Content-Length'][0])" />
<choose>
<when condition="@(int.Parse(context.Variables.GetValueOrDefault<string>('bodySize')) < 52428800)">
<!-- 请求体小于 50MB,允许通过 -->
</when>
<otherwise>
<return-response>
<set-status code="413" reason="Payload Too Large" />
<set-body>@{
return "Maximum allowed size for the POST requests is 52428800 bytes (50 MB). This request has size of " + context.Variables.GetValueOrDefault<string>("bodySize") + " bytes";
}</set-body>
</return-response>
</otherwise>
</choose>
</when>
</choose>
</inbound>
<backend>
<base />
</backend>
<outbound>
</outbound>
<on-error>
<base />
</on-error>
</policies>
[END]
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
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!