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 / TempoTelemetry 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);
}
}
}4. MVC Controller and OpenTelemetry Wiring in Program.cs
MVC Controller (PaymentsController.cs)
C#
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/payments")]
public sealed class PaymentsController : ControllerBase
{
private readonly PaymentWorkflowService _workflowService;
public PaymentsController(PaymentWorkflowService workflowService)
{
_workflowService = workflowService;
}
[HttpPost("authorize")]
public async Task<IActionResult> Authorize(
[FromBody] AuthorizePaymentCommand command,
CancellationToken cancellationToken)
{
if (command is null || string.IsNullOrWhiteSpace(command.ReferenceCode))
{
return BadRequest(new ProblemDetails
{
Title = "Invalid Payment Request",
Detail = "ReferenceCode is required.",
Status = StatusCodes.Status400BadRequest
});
}
// Echo active W3C TraceId in a response header to simplify log/trace correlation
string? traceId = Activity.Current?.TraceId.ToString() ?? HttpContext.TraceIdentifier;
if (!string.IsNullOrWhiteSpace(traceId))
{
Response.Headers["X-Trace-Id"] = traceId;
}
try
{
AuthorizePaymentResult result = await _workflowService.AuthorizeAsync(
command,
actionName: nameof(Authorize),
cancellationToken: cancellationToken);
return string.Equals(result.Outcome, "declined", StringComparison.Ordinal)
? UnprocessableEntity(result)
: Ok(result);
}
catch (ArgumentOutOfRangeException ex)
{
return BadRequest(new ProblemDetails
{
Title = "Invalid Payment Amount",
Detail = ex.Message,
Status = StatusCodes.Status400BadRequest
});
}
}
}Configuring OpenTelemetry Tracing, Metrics, and Logging (Program.cs)
Register MvcPipelineTelemetry as a singleton so the exact same ActivitySource and Meter instances are shared between your application code and the OpenTelemetry SDK. When an OtlpEndpoint is configured (for example, pointing to an OpenTelemetry Collector), exporters attach automatically; if no OTLP endpoint is configured, the host still runs cleanly with local instrumentation active.
C#
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
var telemetry = new MvcPipelineTelemetry();
builder.Services.AddSingleton(telemetry);
builder.Services.AddScoped<PaymentWorkflowService>();
builder.Services.AddControllersWithViews();
string? otlpEndpoint = builder.Configuration["OpenTelemetry:OtlpEndpoint"];
var resourceBuilder = ResourceBuilder.CreateDefault()
.AddService(
serviceName: MvcPipelineTelemetry.ServiceName,
serviceVersion: MvcPipelineTelemetry.ServiceVersion);
builder.Services.AddOpenTelemetry()
.ConfigureResource(rb => rb.AddService(
serviceName: MvcPipelineTelemetry.ServiceName,
serviceVersion: MvcPipelineTelemetry.ServiceVersion))
.WithTracing(tracing =>
{
tracing
.SetResourceBuilder(resourceBuilder)
.AddSource(MvcPipelineTelemetry.ActivitySourceName)
.AddAspNetCoreInstrumentation(opts =>
{
opts.RecordException = true;
})
.AddHttpClientInstrumentation();
if (!string.IsNullOrWhiteSpace(otlpEndpoint))
{
tracing.AddOtlpExporter(o => o.Endpoint = new Uri(otlpEndpoint));
}
})
.WithMetrics(metrics =>
{
metrics
.SetResourceBuilder(resourceBuilder)
.AddMeter(MvcPipelineTelemetry.MeterName)
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation();
if (!string.IsNullOrWhiteSpace(otlpEndpoint))
{
metrics.AddOtlpExporter(o => o.Endpoint = new Uri(otlpEndpoint));
}
});
builder.Logging.AddOpenTelemetry(logging =>
{
logging.SetResourceBuilder(resourceBuilder);
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
if (!string.IsNullOrWhiteSpace(otlpEndpoint))
{
logging.AddOtlpExporter(o => o.Endpoint = new Uri(otlpEndpoint));
}
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }5. End-to-End Integration Testing with WebApplicationFactory<Program> and ActivityListener
Because ActivitySource and Meter are standard .NET APIs, you can attach an ActivityListener and a MeterListener inside an integration test against WebApplicationFactory<Program> to verify that calling an MVC action emits expected spans, tags, and metric measurements end-to-end.
C#
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class OpenTelemetryMvcIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public OpenTelemetryMvcIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task AuthorizePayment_EmitsWorkflowActivitySpanAndRecordsMetrics()
{
var capturedActivities = new List<Activity>();
var recordedCounts = new List<(string InstrumentName, long Value, KeyValuePair<string, object?>[] Tags)>();
using var activityListener = new ActivityListener
{
ShouldListenTo = source => source.Name == MvcPipelineTelemetry.ActivitySourceName,
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStopped = activity =>
{
lock (capturedActivities)
{
capturedActivities.Add(activity);
}
}
};
ActivitySource.AddActivityListener(activityListener);
using var meterListener = new MeterListener
{
InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == MvcPipelineTelemetry.MeterName)
{
listener.EnableMeasurementEvents(instrument);
}
}
};
meterListener.SetMeasurementEventCallback<long>((instrument, measurement, tags, _) =>
{
lock (recordedCounts)
{
recordedCounts.Add((instrument.Name, measurement, tags.ToArray()));
}
});
meterListener.Start();
using HttpClient client = _factory.CreateClient();
var command = new AuthorizePaymentCommand("PAY-9001", 250.00m, "USD");
HttpResponseMessage response = await client.PostAsJsonAsync("/api/payments/authorize", command);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(response.Headers.Contains("X-Trace-Id"));
AuthorizePaymentResult? payload = await response.Content.ReadFromJsonAsync<AuthorizePaymentResult>();
Assert.NotNull(payload);
Assert.Equal("approved", payload.Outcome);
Assert.False(string.IsNullOrWhiteSpace(payload.TraceId));
meterListener.RecordObservableInstruments();
lock (capturedActivities)
{
Assert.Contains(capturedActivities, a =>
a.OperationName == "PaymentWorkflow.Authorize" &&
a.GetTagItem(TelemetryTags.PaymentOutcome)?.ToString() == "approved");
}
lock (recordedCounts)
{
Assert.Contains(recordedCounts, m =>
m.InstrumentName == "portal.mvc.payment.authorizations.total" &&
m.Value == 1);
}
}
}6. Conclusion
Instrumenting ASP.NET Core MVC pipelines with OpenTelemetry (ActivitySource, Meter, and standard ASP.NET Core/HTTP/SQL instrumentation) turns guesswork into clear, actionable diagnostics. Automatic HTTP and client spans link directly with your custom workflow activities and business metrics, TraceId correlation connects logs and responses cleanly, and vendor-neutral exporters let you send telemetry to your chosen collector and dashboarding stack without locking application code to a single monitoring backend.

Join the conversation! Your thoughts help the community grow.