Hinzufügen eines Headers mit eine Korrelations-IDAdd a header containing a correlation id

Dieser Artikel zeigt ein Beispiel für eine Azure API Management-Richtlinie, das veranschaulicht, wie Sie der eingehenden Anforderung einen Header mit einer Korrelations-ID hinzufügen.This article shows an Azure API management policy sample that demonstrates how to add a header containing a correlation id to the inbound request. Um den Code einer Richtlinie festzulegen oder zu bearbeiten, führen Sie die Schritte unter Festlegen oder Bearbeiten von Azure API Management-Richtlinien aus.To set or edit a policy code, follow the steps described in Set or edit a policy. Weitere Beispiele finden Sie unter API Management-Richtlinienbeispiele.To see other examples, see policy samples.

RichtliniePolicy

Fügen Sie den Code in den Block inbound ein.Paste the code into the inbound block.

<!-- The policy defined in this file demonstrates how to add a header containing a correlation id to the inbound request. -->
<!-- The id could be used to correlate requests forwarded by Azure API Management to requests in your backend. -->
<!-- The snippet uses a COMB GUID as an id value for efficient query performance. -->

<!-- NOTE: If COMB format is not needed, context.RequestId should be used as a value of correlation id. -->
<!-- context.RequestId is unique for each request and is stored as part of gateway log records. -->

<!-- Copy the following snippet into the inbound section. Applying this snippet at the global level will ensure that correlation id is added to all requests. -->

<policies>
    <inbound>
        <base />
        <set-header name="correlationid" exists-action="skip">
            <value>@{ 
                var guidBinary = new byte[16];
                Array.Copy(Guid.NewGuid().ToByteArray(), 0, guidBinary, 0, 10);
                long time = DateTime.Now.Ticks;
                byte[] bytes = new byte[6];
                unchecked
                {
                       bytes[5] = (byte)(time >> 40);
                       bytes[4] = (byte)(time >> 32);
                       bytes[3] = (byte)(time >> 24);
                       bytes[2] = (byte)(time >> 16);
                       bytes[1] = (byte)(time >> 8);
                       bytes[0] = (byte)(time);
                }
                Array.Copy(bytes, 0, guidBinary, 10, 6);
                return new Guid(guidBinary).ToString();
            }
            </value>
        </set-header>    
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Nächste SchritteNext steps

Weitere Informationen zu APIM-Richtlinien:Learn more about APIM policies: