检查 Azure API 管理中 traceparent http header 的正确性

Checking correctness of traceparent http header in Azure API Management

有没有办法在转发到后端服务之前使用 Azure API 管理策略检查 traceparent http header 的正确性?

只能手动。您可以将选择策略与策略表达式结合使用,您可以在其中获取 header 的值并使用 C# 代码对其进行验证。然后根据你认为它是否有效采取不同的行动。

我能找到的最好的方法是使用正则表达式创建 API 管理策略。它会发现大部分无效案例,除了一些极端案例。如果提供的 http traceparent header 无效,则 400 - 请求错误,返回响应。

    <choose>
        <when condition="@(!Regex.IsMatch(context.Request.Headers.GetValueOrDefault("traceparent",""), @"^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500)))">
            <return-response>
                <set-status code="400" reason="Bad request - Missing or invalid traceparent http header" />
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-body>@(new JObject(new JProperty("statusCode", 400), new JProperty("message", "Missing or invalid &apos;traceparent&apos; http header for distributed tracing. More information how to supply one at https://www.w3.org/TR/trace-context-1/")).ToString())</set-body>
            </return-response>
        </when>
    </choose>