SkillAgentSearch skills...

HttpUserAgentParser

Parsing HTTP User Agents with .NET

Install / Use

/learn @mycsharp/HttpUserAgentParser
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

MyCSharp.HttpUserAgentParser

Parsing HTTP User Agents with .NET

NuGet

| NuGet | |-| | MyCSharp.HttpUserAgentParser | | MyCSharp.HttpUserAgentParser| dotnet add package MyCSharp.HttpUserAgentParser.MemoryCache | | MyCSharp.HttpUserAgentParser.AspNetCore | dotnet add package MyCSharp.HttpUserAgentParser.AspNetCore |

Usage

string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36";
HttpUserAgentInformation info = HttpUserAgentParser.Parse(userAgent); // alias HttpUserAgentInformation.Parse()

returns

UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
Type = HttpUserAgentType.Browser
Platform = {
    Name = "Windows 10",
    PlatformType = HttpUserAgentPlatformType.Windows
}
Name = "Chrome"
Version = "90.0.4430.212"
MobileDeviceType = null

Dependency Injection and Caching

For dependency injection mechanisms, the IHttpUserAgentParserProvider interface exists, for which built-in or custom caching mechanisms can be used. The use is always:

private IHttpUserAgentParserProvider _parser;
public void MyMethod(string userAgent)
{
    HttpUserAgentInformation info = _parser.Parse(userAgent);
}

If no cache is required but dependency injection is still desired, the default cache provider can simply be used. This registers the HttpUserAgentParserDefaultProvider, which does not cache at all.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpUserAgentParser(); // uses HttpUserAgentParserDefaultProvider and does not cache
}

Likewise, an In Process Cache mechanism is provided, based on a ConcurrentDictionary.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpUserAgentCachedParser(); // uses `HttpUserAgentParserCachedProvider`
    // or
    // services.AddHttpUserAgentParser<HttpUserAgentParserCachedProvider>();
}

This is especially recommended for tests. For web applications, the IMemoryCache implementation should be used, which offers a timed expiration of the entries.

The package MyCSharp.HttpUserAgentParser.MemoryCache is required to use the IMemoryCache. This enables the registration of the IMemoryCache implementation:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpUserAgentMemoryCachedParser();

    // or use options

    services.AddHttpUserAgentMemoryCachedParser(options =>
    {
        options.CacheEntryOptions.SlidingExpiration = TimeSpan.FromMinutes(60); // default is 1 day

        // limit the total entries in the MemoryCache
        //   each unique user agent string counts as one entry
        options.CacheOptions.SizeLimit = 1024; // default is null (= no limit)
    });
}

AddHttpUserAgentMemoryCachedParser registers HttpUserAgentParserMemoryCachedProvider as singleton which contains an isolated MemoryCache object.

ASP.NET Core

For ASP.NET Core applications, an accessor pattern (IHttpUserAgentParserAccessor) implementation can be registered additionally that independently retrieves the user agent based on the HttpContextAccessor. This requires the package MyCSharp.HttpUserAgentParser.AspNetCore

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentMemoryCachedParser() // registers Parser, returns HttpUserAgentParserDependencyInjectionOptions
        // or use any other Parser registration like services.AddHttpUserAgentParser<TParser>(); above
        .AddHttpUserAgentParserAccessor(); // registers IHttpUserAgentParserAccessor, uses IHttpUserAgentParserProvider
}

Now you can use

public void MyMethod(IHttpUserAgentParserAccessor parserAccessor)
{
    HttpUserAgentInformation info = parserAccessor.Get();
}

Telemetry (EventCounters)

Telemetry is opt-in and modular per package.

  • Opt-in: no telemetry overhead unless you explicitly enable it.
  • Modular: each package has its own EventSource name, so you can monitor only what you use.

Enable telemetry (Fluent API)

Core parser telemetry:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentParser()
        .WithTelemetry();
}

MemoryCache telemetry (in addition to core, optional):

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentMemoryCachedParser()
        .WithTelemetry() // core counters (optional)
        .WithMemoryCacheTelemetry();
}

ASP.NET Core telemetry (header present/missing):

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentMemoryCachedParser()
        .AddHttpUserAgentParserAccessor()
        .WithAspNetCoreTelemetry();
}

EventSource names and counters

Core (MyCSharp.HttpUserAgentParser)

  • parse-requests
  • parse-duration (s)
  • cache-concurrentdictionary-hit
  • cache-concurrentdictionary-miss
  • cache-concurrentdictionary-size

MemoryCache (MyCSharp.HttpUserAgentParser.MemoryCache)

  • cache-hit
  • cache-miss
  • cache-size

ASP.NET Core (MyCSharp.HttpUserAgentParser.AspNetCore)

  • useragent-present
  • useragent-missing

Monitor counters

Using dotnet-counters:

dotnet-counters monitor --process-id <pid> MyCSharp.HttpUserAgentParser
dotnet-counters monitor --process-id <pid> MyCSharp.HttpUserAgentParser.MemoryCache
dotnet-counters monitor --process-id <pid> MyCSharp.HttpUserAgentParser.AspNetCore

Telemetry (Meters)

Native System.Diagnostics.Metrics instruments are opt-in per package.

Enable meters (Fluent API)

Core parser meters:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentParser()
        .WithMeterTelemetry();
}

MemoryCache meters:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentMemoryCachedParser()
        .WithMeterTelemetry() // core meters (optional)
        .WithMemoryCacheMeterTelemetry();
}

ASP.NET Core meters:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentMemoryCachedParser()
        .AddHttpUserAgentParserAccessor()
        .WithAspNetCoreMeterTelemetry();
}

Meter names and instruments

Core meter (default: mycsharp.http_user_agent_parser)

  • parse.requests (counter, {call})
  • parse.duration (histogram, s)
  • cache.hit (counter, {call})
  • cache.miss (counter, {call})
  • cache.size (observable gauge, {entry})

MemoryCache meter (default: mycsharp.http_user_agent_parser.memorycache)

  • cache.hit (counter, {call})
  • cache.miss (counter, {call})
  • cache.size (observable gauge, {entry})

ASP.NET Core meter (default: mycsharp.http_user_agent_parser.aspnetcore)

  • user_agent.present (counter, {call})
  • user_agent.missing (counter, {call})

Meter prefix configuration

The default prefix is mycsharp.. The prefix can be configured via DI:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpUserAgentParser()
        .WithMeterTelemetryPrefix("acme.");
}

Rules:

  • "" (empty) is allowed and removes the prefix.
  • Otherwise the prefix must be alphanumeric and end with ..

Example results:

  • Prefix "mycsharp." -> mycsharp.http_user_agent_parser
  • Prefix "" -> http_user_agent_parser
  • Prefix "acme." -> acme.http_user_agent_parser

Export to OpenTelemetry

You can collect these EventCounters via OpenTelemetry metrics.

Packages you typically need:

  • OpenTelemetry
  • OpenTelemetry.Instrumentation.EventCounters
  • an exporter (e.g. OpenTelemetry.Exporter.OpenTelemetryProtocol)

Example (minimal):

using OpenTelemetry.Metrics;
using MyCSharp.HttpUserAgentParser.Telemetry;
using MyCSharp.HttpUserAgentParser.MemoryCache.Telemetry;
using MyCSharp.HttpUserAgentParser.AspNetCore.Telemetry;

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics
            .AddEventCountersInstrumentation(options =>
            {
                options.AddEventSources(
                    HttpUserAgentParserEventSource.EventSourceName,
                    HttpUserAgentParserMemoryCacheEventSource.EventSourceName,
                    HttpUserAgentParserAspNetCoreEventSource.EventSourceName);
            })
            .AddOtlpExporter();
    });

Export to Application Insights

Two common approaches:

  1. OpenTelemetry → Application Insights (recommended)

    • Collect counters with OpenTelemetry (see above)
    • Export using an Azure Monitor / Application Insights exporter (API varies by package/version)
  2. Custom EventListenerTelemetryClient

    • Attach an EventListener
    • Parse the EventCounters payload
    • Forward values as custom metrics

OpenTelemetry listener (recommended)

You can collect EventCounters as OpenTelemetry metrics.

Typical packages:

  • OpenTelemetry
  • `OpenTelemetry.Instrumentation.EventCount
View on GitHub
GitHub Stars75
CategoryDevelopment
Updated23d ago
Forks10

Languages

C#

Security Score

100/100

Audited on Mar 5, 2026

No findings