如何检查头部传递的值是Guid或不在azure APIM策略中,如果没有抛出错误的请求



APIM策略:

<set-variable name="xcid" value="@(context.Request.Headers.GetValueOrDefault("x-correlation-id", Guid.NewGuid().ToString()))" />

<choose>
<!--Request will be rejected if vaild x-correlation-id is not passed -->
<when condition="@((bool)Guid.TryParse(context.Variables["xcid"], out newGuid)== false)">
<return-response>
<set-status code="400" reason="Invalid x-correlation-id is passed please pass valid guid x-correlation-id" />
</return-response>
</when>
</choose>

你的解决方案几乎是正确的。

我假设你想达到以下目标。

  • 如果标题x-correlation-id缺失,创建一个新的指南并继续
  • 如果headerx-correlation-id存在并且值是有效的guid,则继续
  • 否则,拒绝状态码为400的请求

我只需要修改这一行:

<when condition="@(Guid.TryParse(context.Variables.GetValueOrDefault<string>("xcid"), out Guid newGuid) == false)">

变量xcid必须是字符串。将用于输出参数newGuid的数据类型Guid

政策:

<set-variable name="xcid" value="@(context.Request.Headers.GetValueOrDefault("x-correlation-id", Guid.NewGuid().ToString()))" />
<choose>
<!--Request will be rejected if vaild x-correlation-id is not passed -->
<when condition="@(Guid.TryParse(context.Variables.GetValueOrDefault<string>("xcid"), out Guid newGuid) == false)">
<return-response>
<set-status code="400" reason="Invalid x-correlation-id is passed please pass valid guid x-correlation-id" />
</return-response>
</when>
</choose>

最新更新