首页 > 解决方案 > Application Insights - 从 .net 核心中间件添加属性

问题描述

我正在尝试从我们的 .net 核心 MVC 应用程序中获取一些关于应用程序洞察力的额外信息。我找到了以下帖子: 在 Application Insights 指标中为每个请求添加自定义属性

在答案中,他们使用自定义遥测初始化程序,如果您想要一些请求数据或其他东西,它就可以工作。

现在我们的应用程序中有一组中间件。他们将一些标题翻译成可读的内容。

当然,我们可以记录标题并搜索它们可能具有的所有不同值。但是我们希望将结果从中间件转化为应用程序的属性洞察。

任何人都知道如何将中间件的某些结果用于 Application Insights 请求遥测的属性?

标签: .net.net-coreasp.net-core-mvcazure-application-insights

解决方案


从@svoychik 那里得到了正确的想法。中间件将输出值添加到 HttpContext.Items。请参阅示例:

using Microsoft.AspNetCore.Http;
using System.Text;
using System.Threading.Tasks;

namespace Test.API.Middleware
{
    public class ValueMiddleware
    {
        private readonly RequestDelegate next;

        public ApiKeyMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (!context.Items.ContainsKey("ApplicationData"))
            {
                httpContext.Items["ApplicationData"] = "Important Data";
            }
        }
    }
}

然后,当您需要将所有这些项目纳入应用程序洞察力时,您可以使用以下初始化程序:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;

namespace Test.API.TelemetryInitializers : ITelemetryInitializer
{
    public class HttpContextItemsTelemetryInitializer
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public HttpContextItemsTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void Initialize(ITelemetry telemetry)
        {
            var context = httpContextAccessor.HttpContext;
            if (context == null)
            {
                return;
            }

            foreach (var item in context.Items)
            {
                var itemKey = item.Key.ToString();

                // Remove some pollution that Microsoft and the systems adds to the HttpContext Items.
                if (itemKey.Contains("Microsoft") || itemKey.Contains("System"))
                {
                    continue;
                }

                if (!telemetry.Context.GlobalProperties.ContainsKey(itemKey))
                {
                    telemetry.Context.GlobalProperties.Add(itemKey, item.Value.ToString());
                }
            }
        }
    }
}

在 Startup.cs 中设置初始化程序和应用程序洞察力,如下例所示:

using Test.API.TelemetryInitializers;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Test.API
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton<ITelemetryInitializer, HttpContextItemsTelemetryInitializer>();
            services.AddApplicationInsightsTelemetry();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<ValueMiddleware>();
            app.UseMvc();
        }
    }
}

然后它只是将 HttpContext.Items 的所有值添加到您的应用程序洞察力中。


推荐阅读