【问题标题】:Azure apim - Throw error in inbound policyAzure apim - 在入站策略中引发错误
【发布时间】:2022-01-02 04:25:56
【问题描述】:

我一直在尝试通过事件中心记录器记录 apim 请求。我在 onError 策略中有一个记录器对象,它将记录消息。此外,我确实有一些自定义验证,并想登录自定义验证失败。我试图弄清楚我们是否可以引发错误以触发 onError 策略。我似乎没有找到引发/抛出错误的方法。

我唯一的解决方法是为每个自定义验证添加一个记录器对象。

有没有更好的方法。

【问题讨论】:

    标签: xml azure-api-management policies


    【解决方案1】:

    谢谢Joey Cai 和Kai Walter。发布您的建议作为帮助其他社区成员的答案。

    您可以使用<choose> 策略来检测令牌是否无效,如果是,则返回 401 响应。

    <choose>
      <when condition="@((bool)((IResponse)context.Variables["tokenstate"]).Body.As<JObject>()["active"] == false)">
        <return-response response-variable-name="existing response variable">
          <set-status code="401" reason="Unauthorized" />
          <set-header name="WWW-Authenticate" exists-action="override">
            <value>Bearer error="invalid_token"</value>
          </set-header>
        </return-response>
      </when>
    </choose>
    

    检查响应状态码,仅在outbound 部分出错时发送到 eventthub,例如all operations 政策:

    <policies>
        <inbound>
            <base />
        </inbound>
        <backend>
            <base />
        </backend>
        <outbound>
            <base />
            <choose>
                <when condition="@(context.Response.StatusCode.ToString() >= "400")">
                    <log-to-eventhub logger-id ="ehLogger">
                        @(...)
                    </log-to-eventhub>        
                </when>
                <otherwise>
                </otherwise>
            </choose>
        </outbound>
        <on-error>
            <base />
            <log-to-eventhub logger-id ="ehLogger">
                @(...)
            </log-to-eventhub>        
        </on-error>
    </policies>
    

    您可以参考How Do I Throw An Error In Azure API Management Policy?、is it possible to send only error logs to event hub?、Logging all headers and the body of a request from Azure API Management to Azure Event Hub、Error handling in API Management policies和API Management — Errors investigation

    【讨论】:

    • DeepDave-MT,我浏览了链接和代码 sn-p。我知道您不能从字面上抛出/引发会触发抛出策略的错误。看起来我必须在入站、出站和错误策略中引入记录器对象。这将使政策更加庞大。
    • 如果回答对您有帮助,您可以accept it as an answer,以便其他遇到相同问题的人可以找到此解决方案并解决他们的问题
    • 我会说,这解决了我的问题,但我肯定看到了我正在寻找的解决方法。我会将这个答案标记为有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2020-12-21
    • 2017-08-28
    • 2018-12-18
    • 1970-01-01
    • 2023-01-12
    相关资源
    最近更新 更多