2
我想將用戶的「client_id」聲明作爲屬性附加到發送給Application Insights的每個請求。HttpContext和TelemetryInitializer
從我讀過的,我應該實施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;
}
}
}
}
我可以創建一個動作過濾器每次設定的範圍內,但這種感覺可怕:
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);
}
}
有沒有更好的方式來實現我想要做什麼?
不幸的是這似乎不使用ASP.NET的核心/ MVC6兼容。 – davenewza
我問過[另一個問題](http://stackoverflow.com/questions/38418682/webtelemetryinitializerbase-in-asp-net-core-mvc6)。 – davenewza
如何從WebTelemetryInitializerBase中派生如果它的內部函數是內部的(基於2.2.0源)? – UserControl