Application Insights TelemetryInitializer和HttpContext.User

时间:2018-04-11 23:34:07

标签: asp.net-web-api2 azure-application-insights

在WebApi2项目中,我有自定义声明,我希望将其作为每个请求的自定义属性发送。

我实现了TelemetryInitializer,但HttpContext中的User始终为null。

public class MyTelemetryInitializer : ITelemetryInitializer
{   
    var requestTelemetry = telemetry as RequestTelemetry;
    if (requestTelemetry == null) return;

    var user= HttpContext.Current.User;

    // values from header are wokring
     requestTelemetry.Context.Properties["abc"] = HttpContext.Current.Request.Headers.Get("abc");

}

实现这一目标的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

根据您的说明,我查看了Visual Studio Application Insights SDK for .NET Web Applications,发现WebTelemetryInitializerBase.cs有一个抽象方法OnInitializeTelemetry,如下所示:

protected abstract void OnInitializeTelemetry(
            HttpContext platformContext,
            RequestTelemetry requestTelemetry, 
            ITelemetry telemetry);

您可以继承WebTelemetryInitializerBase并覆盖提供OnInitializeTelemetry参数的HttpContext方法,您可以检索自己的声明。

<强>更新

您还可以继承其他继承WebTelemetryInitializerBase的TelemetryInitializers。

例如,UserTelemetryInitializer,您可以按如下方式定义自定义TelemetryInitializer:

public class CustomTelemetryInitializer : UserTelemetryInitializer  //WebTelemetryInitializerBase
{
    protected override void OnInitializeTelemetry(
            HttpContext platformContext,
            RequestTelemetry rootRequestTelemetry,
            ITelemetry telemetry)
    {

        var claim = ((ClaimsIdentity)platformContext.User.Identity).Claims.FirstOrDefault(x => x.Type.Equals("<custom-claim-name>", StringComparison.InvariantCultureIgnoreCase)); ;

        if (claim != null)
        {
            telemetry.Context.Properties["<<custom-claim-name>>"] = claim.Value;
        }
    }
}

此外,您还可以通过here搜索其他TelemetryInitializers。