azure - 为请求事件设置用户名?

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

我在基于 ASP.NET Core Web 主机的 Web 服务中实现了自定义身份验证方案。我想将 Application Insights 添加到此服务。

当我成功验证用户身份时,我会执行以下操作

telemetry.Context.User.Id = authenticatedUserName;

telemetry 对象是我从依赖注入(inject)获得的 TelemetryClient

现在的问题是用户 ID 没有显示在请求中,我不知道为什么。

这有效

customEvents | where user_Id != "" and name  == "MyCustomEvent"

但不是这个

request | where user_Id != ""

或者这个

dependencies | where user_Id != ""

我应该在其他地方设置请求的用户 ID 吗?我不想为此创建自定义事件。

我还尝试在 HttpContext 对象上设置 User 属性,但似乎没有任何效果。

最佳答案

您应该使用ITelemetryInitializer为了您的目的。

以下是我的测试步骤(asp.net core 2.1):

第 1 步:通过右键单击您的项目 -> 添加 -> Application Insights 遥测来添加 Aplication Insights 遥测。截图如下: enter image description here

第 2 步:添加一个实现 ITelemetryInitializer 的新类:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

namespace WebApplication33netcore
{
    public class MyTelemetryInitializer: ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            var request = telemetry as RequestTelemetry;
            if (request != null)
            {
                //set the user id here with your custom value
                request.Context.User.Id = "ivan111";
            }
        }

    }
}

第3步:在Startup.cs的ConfigureServices方法中注册您的遥测初始值设定项。详情参见here :

     public void ConfigureServices(IServiceCollection services)
     {
         services.Configure<CookiePolicyOptions>(options =>
         {

          options.CheckConsentNeeded = context => true;
          options.MinimumSameSitePolicy = SameSiteMode.None;
         });


         services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

         //Add the following code to register your telemetry initializer
         services.AddSingleton<ITelemetryInitializer>(new MyTelemetryInitializer());
    }

第四步:检查测试结果:

在 Visual Studio Application Insights 中搜索: enter image description here

然后在 Analytics 中检查: enter image description here

关于azure - 为请求事件设置用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034944/

相关文章:

azure - Windows Azure 虚拟机上的被动 FTP

entity-framework - 在 Controller 或存储库模式中使用Automapper更好吗?

c# - 如何在 .net Core 应用程序中使用 IConfiguration 绑定(bind)多级配置对象?

azure - 我们可以从Azure无服务器数据库存储过程调用REST api吗

azure - 向 Azure 网站实例发送消息

azure - 引用摘要验证失败

azure - 更改 Application Insights 配置是否会触发应用程序池回收

azure - Application Insight 跨服务和队列关联请求

c# - 在 Windows Azure 上部署您自己的虚拟机

c# - ASP.NET Core EF Code First appsettings.json