Trellis.ServiceLevelIndicators.Asp 10.0.0

dotnet add package Trellis.ServiceLevelIndicators.Asp --version 10.0.0
                    
NuGet\Install-Package Trellis.ServiceLevelIndicators.Asp -Version 10.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Trellis.ServiceLevelIndicators.Asp" Version="10.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Trellis.ServiceLevelIndicators.Asp" Version="10.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Trellis.ServiceLevelIndicators.Asp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Trellis.ServiceLevelIndicators.Asp --version 10.0.0
                    
#r "nuget: Trellis.ServiceLevelIndicators.Asp, 10.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Trellis.ServiceLevelIndicators.Asp@10.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Trellis.ServiceLevelIndicators.Asp&version=10.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Trellis.ServiceLevelIndicators.Asp&version=10.0.0
                    
Install as a Cake Tool

Trellis.ServiceLevelIndicators.Asp

NuGet Package

ASP.NET Core middleware that automatically emits Service Level Indicator (SLI) latency metrics in milliseconds for eligible API operations. Built on the Trellis.ServiceLevelIndicators core library, it helps teams move from generic request timing to service-specific latency metrics with dimensions such as operation, customer, location, and status.

For API versioning support, add Trellis.ServiceLevelIndicators.Asp.ApiVersioning.

When To Use This Package

Choose Trellis.ServiceLevelIndicators.Asp when you are building an ASP.NET Core application and want SLI metrics emitted automatically for MVC controllers or Minimal API endpoints.

Use Trellis.ServiceLevelIndicators if you only need manual measurement in non-HTTP code. Add Trellis.ServiceLevelIndicators.Asp.ApiVersioning when your ASP.NET Core app uses Asp.Versioning and you want the resolved API version emitted as a metric dimension.

Installation

dotnet add package Trellis.ServiceLevelIndicators.Asp
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

The OpenTelemetry hosting and OTLP exporter extensions are separate dependencies. Import OpenTelemetry.Metrics and Trellis.ServiceLevelIndicators. The repository README includes a complete copyable Minimal API setup.

Quick Start — MVC Controllers

// 1. Register with OpenTelemetry
builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics.AddServiceLevelIndicatorInstrumentation();
        metrics.AddOtlpExporter();
    });

// 2. Configure SLI — AddMvc() enables attribute-based overrides
builder.Services.AddServiceLevelIndicator(options =>
{
    options.LocationId = ServiceLevelIndicator.CreateLocationId("public", "westus3");
})
.AddMvc();

// 3. Add the middleware
app.UseServiceLevelIndicator();

Quick Start — Minimal APIs

// Register with OpenTelemetry as shown in the MVC example above.

builder.Services.AddServiceLevelIndicator(options =>
{
    options.LocationId = ServiceLevelIndicator.CreateLocationId("public", "westus3");
});

app.UseServiceLevelIndicator();

// Automatic emission is enabled by default. If you set
// options.AutomaticallyEmitted = false, mark individual endpoints:
app.MapGet("/hello", () => "Hello World!")
    .AddServiceLevelIndicator();

If you configure a custom Meter in ServiceLevelIndicatorOptions, register that same meter with OpenTelemetry by calling AddServiceLevelIndicatorInstrumentation(meter).

Register AddServiceLevelIndicator() once per Minimal API endpoint, either on its group or on the handler. Applying it to both can duplicate parameter metadata and fail endpoint initialization.

ServiceLevelIndicator is a sealed IDisposable registered as a singleton; the DI container disposes it (and the Meter it created) at host shutdown — no manual cleanup needed. A Meter you supply via Options.Meter is owned by you and is never disposed by SLI.

Place UseServiceLevelIndicator() after routing and before endpoint execution so the middleware can read endpoint metadata and measure request handling.

Emitted Metrics

By default, a meter named Trellis.SLI emits the operation.duration histogram in milliseconds. If you configure ServiceLevelIndicatorOptions.Meter, ASP.NET Core SLI metrics are emitted from that meter instead.

Measured HTTP requests emit the following attributes:

Attribute Description
Operation The HTTP method + route template (e.g. GET /teams/{teamId}) — see How Operation is resolved below.
CustomerResourceId The target resource of the operation — see What CustomerResourceId is — and what it is NOT below.
LocationId Where the service is running
Outcome Success, Failure, ClientError, or Ignored; 2xx/3xx responses are Success, common 4xx caller errors are ClientError, 429/5xx and escaping exceptions without an abort are Failure. An observed request abort takes precedence and is Ignored.
http.response.status.code The HTTP response status code; omitted on an aborted request before headers have started, otherwise retained
http.request.method The HTTP method
sli.request.aborted true on an observed abort; absent otherwise
sli.request.abort_exception On an abort with an escaping exception: cancellation for top-level OperationCanceledException (including TaskCanceledException), otherwise other; absent without an exception or abort

No synthetic 499 or abort-related 500 is manufactured. Wrapped cancellations, provider exceptions, and aggregates do not override an observed request abort. Exceptions still propagate. The diagnostic describes the top-level exception's shape, not its cause; other does not prove an independent service failure.

Behavior change: an aborted request with unsent headers no longer emits a phantom status 200. A started response keeps its actual status.

The middleware measures routed endpoints, not genuine route misses. Matched endpoints lacking a bounded template use the existing <unrouted> sentinel.

Optional threshold counts

Configure options.LatencyThresholds.Add(TimeSpan.FromSeconds(2)) to enable operation.duration.threshold.count (Counter<long>, unit {operation}) on the same meter. Each measured request contributes once per configured threshold, with sli.latency.threshold_ms and sli.latency.result = within | exceeded; equality is within. Distinct positive whole-millisecond values are validated and snapshotted at construction; the default is disabled.

Thresholds classify recorded duration; they do not enforce request timeouts, cancel work, or alter HTTP status/outcome.

The counter retains SLI, API-version, abort, and custom dimensions, but excludes HTTP status, HTTP method, and sli.request.abort_exception. The duration histogram is unchanged. A fast failure is not a good event merely because its timing result is within.

Abort-first availability can miss slow dependency outages when callers disconnect before the server fails. Pair availability with a successful-and-fast latency objective that includes slow aborts. The abort diagnostic helps investigation but is not a reliable standalone outage detector. Use the repository's usage reference for the full policy and Azure delta-counter query.

What CustomerResourceId is — and what it is NOT

CustomerResourceId is the target resource of the operation — the noun in the URL path being read or modified — normalized to a stable identifier. It lets you slice SLO compliance per tenant / customer / resource.

For GET /teams/{teamId} made by user xa1 for team team1:

  • ✅ CustomerResourceId = "team1" (the resource being acted on)
  • ❌ NOT "xa1" — that's the caller; keep identities in audit logs/traces, not metric dimensions
  • ❌ NOT a fresh Guid.NewGuid() per request — that explodes metric cardinality
  • ❌ NOT the raw path "/teams/team1" — already covered by Operation

Wire it by decorating the route parameter that names the target resource:

// MVC
[HttpGet("teams/{teamId}")]
[ServiceLevelIndicator(Operation = "GetTeam")]
public IActionResult GetTeam([CustomerResourceId] string teamId) => Ok();

// Minimal API
app.MapGet("/teams/{teamId}",
    ([CustomerResourceId] string teamId) => Results.Ok())
   .AddServiceLevelIndicator("GetTeam");

Or set it imperatively from resolved target metadata via Enrich or HttpContext.GetMeasuredOperation(). A caller's tenant claim is only a valid target when the application guarantees same-tenant operations; cross-tenant callers must not replace the actual target.

How Operation is resolved

Operation is resolved in this order:

  1. [ServiceLevelIndicator(Operation = "...")] attribute (or .AddServiceLevelIndicator("op") for Minimal APIs).
  2. MVC attribute route template (AttributeRouteInfo.Template).
  3. The endpoint's route pattern (RouteEndpoint.RoutePattern.RawText) — covers Minimal APIs and conventional MVC routing. Placeholders such as {id} are preserved, never substituted with the concrete request value.

A trailing slash is trimmed from the resolved template (the literal root / is preserved), so a route group's root endpoint — where the /orders group prefix combines with the / pattern to produce /orders/ — shares one series with /orders instead of emitting a separate POST /orders/.

If none of those yield a bounded template (e.g. a synthetic problem-details endpoint emitted by Asp.Versioning when the API version is invalid), the middleware emits the sentinel "<METHOD> <unrouted>" and logs a one-time warning per endpoint name. If you see <unrouted> in your metrics, an endpoint is missing a route template — fix it by adding an attribute route or moving to a routed endpoint.

Customizations

Exclude endpoints from automatic measurement

Exclude individual endpoints, health checks, or whole route groups:

app.MapHealthChecks("/health")
    .ExcludeFromServiceLevelIndicator();

app.MapGet("/diagnostics", () => Results.Ok())
    .ExcludeFromServiceLevelIndicator();

var internalApi = app.MapGroup("/internal")
    .ExcludeFromServiceLevelIndicator();
internalApi.MapGet("/status", () => Results.Ok());

For MVC, apply the attribute to an action or controller:

[HttpGet("diagnostics")]
[ExcludeFromServiceLevelIndicator]
public IActionResult Diagnostics() => Ok();

Controller attributes and route-group metadata are inherited. Exclusion wins over automatic emission and explicit SLI inclusion metadata, in either registration order; a child inclusion cannot override its parent's exclusion.

Excluded requests still execute normally, but skip the SLI scope, feature attachment, HTTP classification, and all enrichments. They emit no automatic duration, threshold, or measurement-related diagnostic counts, including when the handler throws or the request is aborted. Unlike returning Ignored from a normal-response classifier, this excludes the entire automatic measurement path.

Other ASP.NET Core/Application Insights telemetry is unchanged. Explicit core measurements remain available. HttpContext.TryGetMeasuredOperation(...) returns false on an excluded endpoint unless application code supplies its own feature.

HTTP method dimension

http.request.method is emitted by default. AddHttpMethod() remains available as a no-op for older setup code.

Customize HTTP classification

Override a normal-response mapping while retaining every other built-in mapping:

builder.Services.AddServiceLevelIndicator(options => options.LocationId = locationId)
    .ClassifyHttpOutcome((context, defaultOutcome) =>
        context.Response.StatusCode == 429 && IsCallerQuotaRejection(context)
            ? SliOutcome.ClientError
            : defaultOutcome);

IsCallerQuotaRejection is application-specific limiter metadata. A caller quota may be ClientError; service-capacity rejection should remain Failure. HttpOutcomeClassifier.ClassifyStatusCode(int) exposes the default mapper.

The existing one-argument callback remains a replacement classifier. Last fluent registration wins across both overloads. For direct options configuration, ServiceLevelIndicatorHttpOptions.ClassifyOutcomeWithDefault takes precedence over ClassifyOutcome when both are set. Neither callback overrides request aborts or escaping exceptions.

If a callback throws or returns an undefined outcome, the middleware logs a warning, uses the already-computed built-in status outcome, and continues enrichment. It does not try a lower-priority callback or turn the handler's completion into a classifier exception. This ambient HTTP policy differs from explicit core result selectors, whose errors still propagate.

Fallback changes the SLO population. A custom-ignored /health request can become Success; a custom client-error 429 can become Failure. Monitor HttpOutcomeClassificationFailed (EventSource event 3), which includes the fallback outcome and is emitted independently of warning-log filtering. Enrichment errors likewise emit EnrichmentFailed (event 4), even with a no-op logger. Enable collection of provider Trellis-ServiceLevelIndicators to observe these events.

Enrichment and diagnostic-logger failures do not replace handler exceptions or change responses. A broken logger is reported through EventSource provider Trellis-ServiceLevelIndicators, event 2 (DiagnosticLoggingFailed). Recording failures are reported by the core and are not thrown from measurement disposal; failed recording is not retried.

ASP uses the public ServiceLevelIndicatorEventSource contract and public outcome validation, not core internals; compatible core updates do not require an exact-version package pin. Exception-text fields are capped at 2048 UTF-16 code units, not redacted, and can still contain request data. A recording-provider failure after histogram delivery can leave threshold counts behind; cross-instrument reconciliation is not guaranteed on failure.

Enrich with custom data

Enrich receives a WebEnrichmentContext exposing HttpContext, SetCustomerResourceId, and AddAttribute. EnrichAsync receives that context and a cancellation token and returns ValueTask. Add bounded dimensions without replacing the target resource:

builder.Services.AddServiceLevelIndicator(options => { /* ... */ })
    .AddMvc()
    .Enrich(context =>
    {
        var tier = context.HttpContext.User.FindFirst("tier")?.Value switch
        {
            "free" => "free",
            "standard" => "standard",
            "premium" => "premium",
            _ => "unknown"
        };
        context.AddAttribute("CallerTier", tier);
    });

Enrichment runs after endpoint handling and can overwrite a resource already extracted from route metadata. Only call SetCustomerResourceId with the resolved target, not the caller's tenant unless same-tenant semantics are guaranteed. See What CustomerResourceId is — and what it is NOT.

Enrich and EnrichAsync delegates are skipped once request cancellation is observed. To preserve already-resolved metadata on aborts, implement IEnrichment<WebEnrichmentContext> with EnrichOnCancellation => true and register it in DI. Only opt in for bounded, cancellation-safe metadata access without I/O; the canceled token is still passed. Skipped enrichments do not prevent later cancellation-safe enrichments from running. The API-version package already opts in.

Override the operation name

[HttpGet("MyAction")]
[ServiceLevelIndicator(Operation = "MyCustomName")]
public IActionResult Get() => Ok();

Set CustomerResourceId from a route parameter

[HttpGet("teams/{teamId}")]
public IActionResult GetTeam([CustomerResourceId] string teamId) => Ok();

Or imperatively:

HttpContext.GetMeasuredOperation().CustomerResourceId = customerResourceId;

Add custom attributes from route parameters

Parameters decorated with [Measure] are automatically added as metric dimensions:

[HttpPost("projects/{projectId}/sync/{mode:regex(^(quick|standard|slow)$)}")]
public IActionResult Sync(
    [CustomerResourceId] string projectId,
    [Measure("SyncMode")] string mode) => Ok();

Use stable target identifiers and bounded categories such as these three sync modes, not personal names or arbitrary text.

Add custom attributes manually

HttpContext.GetMeasuredOperation().AddAttribute("CustomKey", value);

// Safe version for middleware (won't throw if SLI is not configured for the route)
if (HttpContext.TryGetMeasuredOperation(out var op))
    op.AddAttribute("CustomKey", value);

Cardinality Guidance

Required tags must be stable and meaningful:

  • Operation is bounded for you by the route-template resolver above (one series per HTTP method × route template). Watch your metrics for the <unrouted> sentinel — it means an endpoint is missing a route template.
  • LocationId is set once per process from configuration — naturally bounded.
  • CustomerResourceId is your responsibility. Use a stable tenant / subscription / resource identifier; do not use per-request GUIDs, timestamps, request IDs, or raw user input. High-cardinality customer resources are acceptable when they are stable, meaningful, and supported by your metrics backend.

The same discipline applies to [Measure] parameters and any custom attributes you add via AddAttribute(...).

Opt-in mode

To disable automatic SLI emission on all controllers:

options.AutomaticallyEmitted = false;

Then add [ServiceLevelIndicator] only to the controllers you want measured.

Optional AgentDocs setup

This package includes a versioned API reference, but restoring it does not install agent instructions. To opt in, restore your consuming project or solution, then run from its Git root:

dotnet new tool-manifest --output .config
dotnet tool install Trellis.AgentDocs --version 1.0.2 --tool-manifest .config/dotnet-tools.json
dotnet tool run agentdocs init <solution-or-project>

If the repository already has .config/dotnet-tools.json, reuse it instead of creating another manifest. Restoring a package never activates its guide: init lists Trellis.ServiceLevelIndicators.Asp as pending and prints the package IDs to add to approvedPackages in .agentdocs/policy.json. Add the ones you trust, then run dotnet tool run agentdocs sync to install the guides under Git-root .agentdocs/. The guide is on-demand: the generated index describes it, and an agent opens it when its task concerns SLI metrics. After a package upgrade, run dotnet restore --force and then dotnet tool run agentdocs sync.

Further Reading

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Trellis.ServiceLevelIndicators.Asp:

Package Downloads
Trellis.ServiceLevelIndicators.Asp.ApiVersioning

Adds the resolved API version as the http.api.version SLI dimension when the ASP.NET Core app uses Asp.Versioning, including aborted requests and opt-in threshold counts. Extension package for Trellis.ServiceLevelIndicators.Asp.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.0 193 10/19/2026
10.0.0-preview.43 87 10/17/2026
10.0.0-preview.37 72 10/16/2026
10.0.0-preview.34 171 10/4/2026
10.0.0-preview.32 243 10/1/2026
10.0.0-preview.31 74 9/30/2026
10.0.0-preview.30 78 9/29/2026
10.0.0-preview.29 81 9/28/2026
10.0.0-preview.28 73 9/28/2026
10.0.0-preview.27 85 9/28/2026
10.0.0-preview.26 514 7/6/2026
10.0.0-preview.25 233 6/24/2026
10.0.0-preview.24 204 6/19/2026
10.0.0-preview.21 140 5/19/2026
10.0.0-preview.10 106 4/24/2026
10.0.0-preview.9 88 4/23/2026