HttpContext and TelemetryInitializer

后端 未结 3 609
余生分开走
余生分开走 2020-12-06 18:20

I want to attach the user\'s \"client_id\" claim as a property to every request sent to Application Insights.

From what I\'ve read, I should be implementing IT

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 19:03

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

提交回复
热议问题