How to Add User-Agent to Application Insights Telemetry in C# Using Middleware

By FoxLearn 1/9/2025 3:44:14 AM   23
To achieve this, we’ll implement a custom middleware.

Middleware in ASP.NET Core runs on every HTTP request and response, providing an excellent spot for collecting or modifying request data before passing it along the pipeline.

In this example, I'll write middleware that collects a custom header from incoming requests and adds it as a custom property to the RequestTelemetry in Application Insights.

You should have Application Insights enabled in your application.

CREATE THE MIDDLEWARE

using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Example
{
    public class TelemetryMiddleware
    {
        private readonly RequestDelegate _next;

        public TelemetryMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            context.Request.EnableBuffering();
            AddUserAgentToApplicationInsights(context);
            await _next(context);
        }

        private static void AddUserAgentToApplicationInsights(HttpContext context)
        {
            // You can add custom logic to filter requests, e.g., only for POST methods
            if (context.Request.Method == HttpMethods.Post)
            {
                var telemetry = context.Features.Get<RequestTelemetry>();
                if (telemetry == null) return;

                telemetry.Properties.Add("UserAgent", context.Request.Headers["User-Agent"]);
            }
        }
    }
}

In this example:

  • We check if the request method is POST and then access the RequestTelemetry object.
  • If RequestTelemetry is available, we add the User-Agent header to the custom properties.

You can modify this to handle different HTTP methods or other conditions as needed.

ENABLE THE MIDDLEWARE

Now, register the middleware in the Configure method of your Startup or Program class:

public static void Main(string[] args)
{
    var builder = CreateHostBuilder(args);
    var startup = new Startup(builder.Configuration, builder.Environment);

    WebApplication app = builder.Build();
    app.UseMiddleware<TelemetryMiddleware>();  // Add the middleware here
    app.Run();
}

After adding the middleware and running your application, each POST request logged in Application Insights will include the User-Agent as a custom property.