Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...