Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c# - HttpContext and TelemetryInitializer

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 ITelemetryInitializer but I need the HttpContext for the request in order to retrieve "client_id". See my initialiser:

public class ClaimTelemetryInitializer : ITelemetryInitializer
{
    public HttpContext HttpContext { get; set; }

    public void Initialize(ITelemetry telemetry)
    {
        this.AddTelemetryContextPropertFromClaims(telemetry, "client_id");
    }

    private void AddTelemetryContextPropertFromClaims(ITelemetry telemetry, string claimName)
    {
        if (HttpContext != null)
        {
            var requestTelemetry = telemetry as RequestTelemetry;

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

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

I could create an action filter to set the context each time, but this feels awful:

public class TrackClaimsAttribute : ActionFilterAttribute
{
    public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var initialiser = TelemetryConfiguration.Active.TelemetryInitializers.OfType<ClaimTelemetryInitializer>().Single();

        initialiser.HttpContext = context.HttpContext;

        return base.OnActionExecutionAsync(context, next);
    }
}

Is there a better way to achieve what I want to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...