'how to check value passed in header is Guid or not in azure APIM policy if not throw bad request

APIM policy:

<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>


Solution 1:[1]

Your solution was almost correct.

I assume you want to achieve the following.

  • if header x-correlation-id is missing, create a new guid and proceed
  • if header x-correlation-id is present and the value is a valid guid, then proceed
  • otherwise, reject the request with a status code 400

I had to fix only this line:

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

The variable xcid has to be string. The datatype Guid his to be used for the out parameter newGuid.

Policy:

    <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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Markus Meyer