【Azure APIM】APIM Policy是否可以阻止大于50MB文件的上傳呢?
問題描述
在使用 Azure API Management(APIM)時,如何防止客戶端發(fā)送過大的 POST 請求?例如,如何阻止任何超過 50MB 的文件上傳請求,以避免資源浪費或潛在的服務(wù)中斷。
問題解答
可以的。通過在 Azure APIM 中配置策略(Policy)來實現(xiàn)對請求體大小的限制。
具體做法如下:
1: 依賴 Content-Length 頭部信息:通過檢查請求頭中的 Content-Length 值來判斷請求體大小。
2: 使用 Inbound 策略進行判斷:在 API 的 inbound 策略中添加如下邏輯:
- 判斷請求是否為 POST。
- 獲取 Content-Length 值。
- 如果請求體大小超過 50MB(即 52428800 字節(jié)),則返回 HTTP 狀態(tài)碼 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
當(dāng)在復(fù)雜的環(huán)境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 云中,恰是如此!

浙公網(wǎng)安備 33010602011771號