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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…