HttpContext and TelemetryInitializer

I wish this were designed into AppInsights but you can directly use the static HttpContext.Current. You can use it's per-request Items dictionary as a short term (near stateless) storage space to deliver your custom values to the custom telemetry handler.

So try

class AppInsightCustomProps : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        // Is this a TrackRequest() ?
        if (requestTelemetry == null) return;

        var httpCtx = HttpContext.Current;
        if (httpCtx != null)
        {
            var customPropVal = (string)httpCtx.Items["PerRequestMyCustomProp"];
            if (!string.IsNullOrWhiteSpace(customPropVal))
            {
                requestTelemetry.Properties["MyCustomProp"] = customPropVal;
            }
        }
    }
}

And to program the desired custom property, anywhere in your request pipeline have something like

if (HttpContext.Current != null)
{
    HttpContext.Current.Items["PerRequestMyCustomProp"] = myCustomPropValue;
}

I would suggest to inject an HttpContextAccessor instance in the ClaimTelemetryInitializer class's constructor, and then you could use it to extract values from the HttpContext. Or, even better, create a base class for your TelemetryInitializer, and use it's constructor to inject the HttpContextAccessor instance.

For example:

    protected ClaimTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        var context = this.httpContextAccessor.HttpContext;
        if (context == null)
        {
            return;
        }

        var claim = context.User.Claims.SingleOrDefault(x => x.Type.Equals(claimName, StringComparison.InvariantCultureIgnoreCase));
        //Do logic here...
    }

You should implement the WebTelemetryInitializerBase which provides you the HttpContext.

Your code should look like:

public class ClaimTelemetryInitializer : WebTelemetryInitializerBase
{
    protected override void OnInitializeTelemetry(
            HttpContext platformContext,
            RequestTelemetry rootRequestTelemetry, 
            ITelemetry telemetry) {

            var claim = HttpContext.User.Claims.SingleOrDefault(x => x.Type.Equals(claimName, StringComparison.InvariantCultureIgnoreCase));

            if (claim != null)
            {
                telemetry.Context.Properties[claimName] = claim.Value;
            }
    }
}