gpt4 book ai didi

c# - HttpContext和TelemetryInitializer

转载 作者:行者123 更新时间:2023-12-04 22:57:41 25 4
gpt4 key购买 nike

我想将用户的“client_id”声明作为属性附加到发送给Application Insights的每个请求中。

从我所读的内容中,我应该实现ITelemetryInitializer,但是我需要用于请求的HttpContext才能检索“client_id”。看到我的初始化器:

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

我可以创建一个 Action 过滤器来每次设置上下文,但这感觉很糟糕:
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);
}
}

有没有更好的方法来实现我想做的事?

最佳答案

您应该实现为您提供HttpContext的WebTelemetryInitializerBase

您的代码应如下所示:

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

关于c# - HttpContext和TelemetryInitializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38413032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com