How to Add User-Agent to Application Insights Telemetry in C# Using Middleware
By FoxLearn 1/9/2025 3:44:14 AM 23
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.
- Boosting Web Performance with MapStaticAsset in ASP.NET Core
- How to use HttpClient and IHttpClientFactory in .NET Core
- How to implement a distributed cache in ASP.NET Core
- How to build custom middleware in ASP.NET Core
- How to use Lamar in ASP.NET Core
- How to use NCache in ASP.NET Core
- How to use MiniProfiler in ASP.NET Core
- Using cookies in ASP.NET Core