2016-07-16 60 views
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); 
    } 
} 

有沒有更好的方式來實現我想要做什麼?

回答

4

您應該實現爲您提供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; 
      } 
    } 
} 
+0

不幸的是這似乎不使用ASP.NET的核心/ MVC6兼容。 – davenewza

+0

我問過[另一個問題](http://stackoverflow.com/questions/38418682/webtelemetryinitializerbase-in-asp-net-core-mvc6)。 – davenewza

+1

如何從WebTelemetryInitializerBase中派生如果它的內部函數是內部的(基於2.2.0源)? – UserControl