When an ASP.NET Core MVC action slows down or fails in production, HTTP access logs alone rarely tell you why. A request might spend 15 ms in MVC model binding and action execution, 640 ms waiting on a slow SQL query or downstream HTTP call, or fail inside a domain workflow step that wasn't tagged with business context.
OpenTelemetry gives ASP.NET Core MVC applications vendor-neutral observability across traces (ActivitySource + Activity spans), metrics (Meter, Counter<T>, and Histogram<double>), and logs. Combining automatic instrumentation (AddAspNetCoreInstrumentation, AddHttpClientInstrumentation, AddSqlClientInstrumentation) with custom MVC spans and business metrics lets you trace requests end-to-end, measure p95/p99 latency distributions per action and outcome, and export telemetry cleanly via OTLP or Prometheus to your observability stack.
1. Architectural Blueprint & Telemetry Signal Flow
Plaintext
Incoming HTTP Request (with W3C traceparent / tracestate)
│
▼
[ASP.NET Core Instrumentation] ── starts root HTTP server span & HTTP duration metric
│
▼
[MVC Action / Workflow Instrumentation]
├─ Starts child Activity span on custom ActivitySource (e.g., "Payments.Authorize")
├─ Records domain tags (payment.currency, payment.outcome, mvc.action)
├─ Captures exceptions via Activity.AddException / SetStatus(ActivityStatusCode.Error)
└─ Records custom Meter instruments:
• Counter<long>: payments.authorizations.total (tagged by outcome & currency)
• Histogram<double>: payments.authorization.duration.ms (tagged by action & outcome)
│
▼
[Outbound HttpClient / SQL Client Instrumentation] ── propagates W3C trace context & records child spans
│
▼
[OpenTelemetry Exporter (OTLP / Prometheus)] ──> Collector / Grafana / Prometheus / Tempo
Telemetry Signal |
.NET API Primitive |
What It Answers in MVC Pipelines |
Distributed Traces |
|
Where did time go across HTTP ingress, MVC action logic, database/external calls, and retries? |
Custom Metrics |
|
How often do specific outcomes occur, and what is the latency distribution (p50/p95/p99) per action? |
Structured Logs |
|
What specific diagnostic details accompanied a warning or failure on that exact trace? |
2. Custom Telemetry Definitions (ActivitySource and Meter)
Centralizing ActivitySource names, Meter names, metric instruments, and tag/attribute keys in a dedicated telemetry class prevents string typos across controllers, services, and Program.cs registrations.
C#
using System.Diagnostics;
using System.Diagnostics.Metrics;
public sealed class MvcPipelineTelemetry : IDisposable
{
public const string ServiceName = "Portal.Mvc.Observability";
public const string ServiceVersion = "1.0.0";
public const string ActivitySourceName = "Portal.Mvc.Workflows";
public const string MeterName = "Portal.Mvc.Metrics";
public ActivitySource ActivitySource { get; }
public Meter Meter { get; }
public Counter<long> PaymentAuthorizationCounter { get; }
public Histogram<double> PaymentAuthorizationDurationMs { get; }
public MvcPipelineTelemetry()
{
ActivitySource = new ActivitySource(ActivitySourceName, ServiceVersion);
Meter = new Meter(MeterName, ServiceVersion);
PaymentAuthorizationCounter = Meter.CreateCounter<long>(
name: "portal.mvc.payment.authorizations.total",
unit: "{authorization}",
description: "Total payment authorization attempts processed through the MVC pipeline.");
PaymentAuthorizationDurationMs = Meter.CreateHistogram<double>(
name: "portal.mvc.payment.authorization.duration.ms",
unit: "ms",
description: "Duration of payment authorization workflow execution in milliseconds.");
}
public void Dispose()
{
ActivitySource.Dispose();
Meter.Dispose();
}
}
public static class TelemetryTags
{
public const string MvcAction = "mvc.action";
public const string PaymentCurrency = "payment.currency";
public const string PaymentOutcome = "payment.outcome";
public const string PaymentAmountTier = "payment.amount_tier";
}
3. Instrumenting an MVC Workflow Service with Spans and Metrics
Wrapping business operations in ActivitySource.StartActivity(...) creates child spans automatically linked to the active HTTP request's Activity.Current, while Stopwatch.GetTimestamp() / Stopwatch.GetElapsedTime(...) records accurate high-resolution durations to the Histogram<double> and increments the Counter<long>.
C#
using System.Diagnostics;
using System.Globalization;
public sealed record AuthorizePaymentCommand(
string ReferenceCode,
decimal Amount,
string Currency
);
public sealed record AuthorizePaymentResult(
Guid AuthorizationId,
string ReferenceCode,
decimal Amount,
string Currency,
string Outcome,
string TraceId
);
public sealed class PaymentWorkflowService
{
private readonly MvcPipelineTelemetry _telemetry;
private readonly ILogger<PaymentWorkflowService> _logger;
public PaymentWorkflowService(
MvcPipelineTelemetry telemetry,
ILogger<PaymentWorkflowService> logger)
{
_telemetry = telemetry;
_logger = logger;
}
public async Task<AuthorizePaymentResult> AuthorizeAsync(
AuthorizePaymentCommand command,
string actionName,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
long startTimestamp = Stopwatch.GetTimestamp();
string normalizedCurrency = string.IsNullOrWhiteSpace(command.Currency)
? "USD"
: command.Currency.Trim().ToUpperInvariant();
string amountTier = command.Amount switch
{
<= 100m => "small",
<= 5_000m => "medium",
_ => "large"
};
using Activity? activity = _telemetry.ActivitySource.StartActivity(
name: "PaymentWorkflow.Authorize",
kind: ActivityKind.Internal);
activity?.SetTag(TelemetryTags.MvcAction, actionName);
activity?.SetTag(TelemetryTags.PaymentCurrency, normalizedCurrency);
activity?.SetTag(TelemetryTags.PaymentAmountTier, amountTier);
activity?.SetTag("payment.reference_code", command.ReferenceCode);
string outcome = "approved";
try
{
if (command.Amount <= 0m)
{
outcome = "rejected_invalid_amount";
activity?.SetTag(TelemetryTags.PaymentOutcome, outcome);
activity?.SetStatus(ActivityStatusCode.Error, "Payment amount must be greater than zero.");
throw new ArgumentOutOfRangeException(nameof(command.Amount), "Amount must be greater than zero.");
}
if (string.Equals(command.ReferenceCode, "DECLINE-TEST", StringComparison.OrdinalIgnoreCase))
{
outcome = "declined";
activity?.SetTag(TelemetryTags.PaymentOutcome, outcome);
activity?.SetStatus(ActivityStatusCode.Ok, "Payment declined by business rule.");
var declinedResult = new AuthorizePaymentResult(
AuthorizationId: Guid.Empty,
ReferenceCode: command.ReferenceCode.Trim().ToUpperInvariant(),
Amount: decimal.Round(command.Amount, 2, MidpointRounding.AwayFromZero),
Currency: normalizedCurrency,
Outcome: outcome,
TraceId: Activity.Current?.TraceId.ToString() ?? string.Empty);
return declinedResult;
}
// Simulate downstream authorization work
await Task.Delay(TimeSpan.FromMilliseconds(15), cancellationToken);
activity?.SetTag(TelemetryTags.PaymentOutcome, outcome);
activity?.SetStatus(ActivityStatusCode.Ok);
var approvedResult = new AuthorizePaymentResult(
AuthorizationId: Guid.NewGuid(),
ReferenceCode: command.ReferenceCode.Trim().ToUpperInvariant(),
Amount: decimal.Round(command.Amount, 2, MidpointRounding.AwayFromZero),
Currency: normalizedCurrency,
Outcome: outcome,
TraceId: Activity.Current?.TraceId.ToString() ?? string.Empty);
_logger.LogInformation(
"Authorized payment {AuthorizationId} for ref {ReferenceCode} ({Amount} {Currency}) with outcome {Outcome}.",
approvedResult.AuthorizationId,
approvedResult.ReferenceCode,
approvedResult.Amount.ToString("0.00", CultureInfo.InvariantCulture),
approvedResult.Currency,
outcome);
return approvedResult;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
if (outcome == "approved")
{
outcome = "error";
}
activity?.SetTag(TelemetryTags.PaymentOutcome, outcome);
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
activity?.AddEvent(new ActivityEvent("payment.authorization.failed", tags: new ActivityTagsCollection
{
{ "exception.type", ex.GetType().FullName },
{ "exception.message", ex.Message }
}));
throw;
}
finally
{
double elapsedMs = Stopwatch.GetElapsedTime(startTimestamp).TotalMilliseconds;
var metricTags = new TagList
{
{ TelemetryTags.MvcAction, actionName },
{ TelemetryTags.PaymentCurrency, normalizedCurrency },
{ TelemetryTags.PaymentOutcome, outcome }
};
_telemetry.PaymentAuthorizationCounter.Add(1, metricTags);
_telemetry.PaymentAuthorizationDurationMs.Record(elapsedMs, metricTags);
}
}
}
Join the conversation! Your thoughts help the community grow.