如何使用 azure API Management 为 APIs 中的每个方法设置 405 Method Not Allowed

How to setup 405 Method Not Allowed for each of the methods in APIs using azure API Management

在 azure 中 API 管理如何设置 405(方法不允许)策略。我正在使用 azure API 管理 APIs 并添加不同的策略,如 jwt 验证、IP 过滤、速率限制等等。但是我找不到添加 APIM 中不允许的 405 方法的方法。我想为每种方法设置它。这意味着我想阻止来自 APIM 的传入的无法识别的方法请求。 (例如:Get instead of POST (Throws 405 method not allowed from APIM). 目前 APIM 将错误的方法传递给后端,它 returns 来自 returns 的 404应用程序。任何人都知道我们如何阻止来自 APIM 端和 returns 405 的错误请求,而不是将其传递给后端和 returns 404?

您可以使用 Control Flow policy along with the Context Variable on the Inbound policy of each Method to intercept any requests that don't match the defined http method and then use a Set Status 策略来 return 405。因此对于 GET 方法,类似于:

<policies>
  <inbound>
    <choose>
      <when condition="@(context.Request.Method.ToString() != "GET")">
        <return-response>
          <set-status code="405" reason="No Content" />
        </return-response>
      </when>
    </choose>
    <base />
  </inbound>
  ... rest of policies
</policies>

如果您有多个具有相同路径的方法,您可能需要在 API 级别而不是方法级别应用此方法,并使条件 等于方法未使用而不是不等于正在使用的方法

要在 API 级别设置它并检查未使用的方法集合,请按照以下行创建策略:

<policies>
  <inbound>
    <choose>
      <when condition="@{
        ICollection<string>  disallowedMethods = new List<string>() { "POST", "PUT" };
        return disallowedMethods.Contains(context.Request.Method.ToString());           
      }">
        <return-response>
          <set-status code="405" reason="No Content" />
        </return-response>
      </when>
    </choose>
    <base />
  </inbound>
  ... rest of policies
</policies>

此示例中未使用的 http 方法是 POST 和 PUT,但您可以将列表更改为适用于您的用例的任何内容。