How to Add User-Agent to Application Insights Telemetry in C# Using Middleware
By Tan Lee Published on Jan 09, 2025 379
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 theRequestTelemetry
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.
- How to Initialize TagHelpers in ASP.NET Core with Shared Data
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core