azure - 从 ASP.NET Core 填充 Application Insights 中的用户 ID 字段

标签 azure asp.net-core azure-application-insights asp.net-core-2.2 scrutor

我希望能够使用我的真实用户名数据填充 Application Insights 中的“用户 ID”字段。这是一个内部应用程序,因此简单的用户名字段的隐私问题没有任何意义。

据我所知,所有在线可用的解决方案都严格适用于 .NET Framework,而不是 .NET Core。

您可以找到this solution在一些地方,包括 GitHub 上的一些旧的 AI 文档。但是,当我运行它时,我在启动时收到错误,表明单例 Not Acceptable 对作用域对象 IHttpContextAccessor 的依赖,这当然是合乎逻辑的。我不明白这是如何工作的,除非 .NET Core 的早期版本的 DI 允许(我使用的是 2.2)。

This issue on GitHub有点说明了问题,但在 AI 团队指出你必须使用单例之后,它就被关闭了。我尝试了 OP 和第一个响应中内容的变体,当代码运行时,AI 上的用户 ID 字段继续填充乱码数据。

有没有办法让 AI 中的用户 ID 字段填充对来自 ASP.NET Core 应用程序的服务器请求有用的内容?

编辑

在看到下面的答案后,我的代码应该可以正常工作,我回去并意识到异常消息没有特别提到 IHttpContextAccessor:

System.InvalidOperationException: 'Cannot consume scoped service 'Microsoft.ApplicationInsights.Extensibility.ITelemetryInitializer' from singleton 'Microsoft.Extensions.Options.IConfigureOptions`1[Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration]'.'

现在,我的代码看起来与下面 @PeterBons 的答案几乎相同,所以从表面上看,这个异常没有任何意义。 TelemetryConfiguration 事件没有出现在我的代码中。但后来我想起我正在使用 Scrutor 在 Startup 中懒惰地进行 DI 注册:

    services.Scan(scan => scan
        .FromAssembliesOf(typeof(Startup), typeof(MyDbContext))
        .AddClasses()
        .AsSelfWithInterfaces().WithScopedLifetime());

我认为问题是我需要将 ITelemetryInitializer 注册为 Singleton,并且此代码无意中将其取消或重新注册为作用域。所以我将最后两行更改为:

        .AddClasses(f => f.Where(t => t != typeof(RealUserAIProvider)))
        .AsSelfWithInterfaces().WithScopedLifetime());

而且它成功了。我不会删除上面的错误,而是将其保留。 @PeterBons 下面的回答仍然对其他人有帮助,也许我对 Scrutor 的困惑也会对某人有所帮助。

最佳答案

您不必将 HttpContextAccessor 注册为作用域依赖项。只需使用单例即可。

我们在生产中使用了这个:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

与此初始值设定项结合使用:

public class SessionDetailsTelemetryEnrichment : TelemetryInitializerBase
{
    public SessionDetailsTelemetryEnrichment(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
    {

    }

    protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
    {
        telemetry.Context.User.AuthenticatedUserId =
            platformContext.User?.Claims.FirstOrDefault(c => c.Type == "Username")?.Value ?? string.Empty;

    }
}

关于azure - 从 ASP.NET Core 填充 Application Insights 中的用户 ID 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979452/

相关文章:

testing - XUnit DI 通过覆盖启动文件(.net 核心)

c# - 如何在 Visual Studio ASP.NET Core Web 项目中每次重建时使 Kestrel 控制台窗口自动关闭/重置?

azure-application-insights - Application Insights - 仅获取客户端数据,不获取服务器数据。

azure - 在 Application Insights for Worker Service 应用程序中配置日志级别

mysql - Azure Application Insights Kusto 语言按时间生成值进行汇总

c# - 如何删除 Log Analytics 数据收集器 API 创建的自定义日志

Azure SQL DACPAC 部署失败 - 不支持目标架构的兼容性级别。

python - Azure(函数)参数在 Python 中声明,但不在 function.json 中声明

azure - 为什么 App Insights 仅显示警告和错误跟踪级别?那么更低的水平呢?

c# - ASP.NET Core Web API + 对预检请求的 Angular 响应未通过访问控制检查 : Redirect is not allowed for a preflight request