diff --git a/tracer/src/Datadog.Trace/PlatformHelpers/AspNetCoreHttpRequestHandler.cs b/tracer/src/Datadog.Trace/PlatformHelpers/AspNetCoreHttpRequestHandler.cs index 56453950f888..de5c419a77ff 100644 --- a/tracer/src/Datadog.Trace/PlatformHelpers/AspNetCoreHttpRequestHandler.cs +++ b/tracer/src/Datadog.Trace/PlatformHelpers/AspNetCoreHttpRequestHandler.cs @@ -43,14 +43,30 @@ public AspNetCoreHttpRequestHandler( public string GetDefaultResourceName(HttpRequest request) { + // Be defensive: in some edge cases the HttpRequest object may be null (e.g., + // framework- or host-specific error paths). Avoid throwing and return a safe default. + if (request is null) + { + return "UNKNOWN /"; + } + string httpMethod = request.Method?.ToUpperInvariant() ?? "UNKNOWN"; - string absolutePath = request.PathBase.HasValue - ? request.PathBase.ToUriComponent() + request.Path.ToUriComponent() - : request.Path.ToUriComponent(); + string absolutePath; + try + { + absolutePath = request.PathBase.HasValue + ? request.PathBase.ToUriComponent() + request.Path.ToUriComponent() + : request.Path.ToUriComponent(); + } + catch + { + // If anything goes wrong building the path, fall back to root + absolutePath = "/"; + } - string resourceUrl = UriHelpers.GetCleanUriPath(absolutePath) - .ToLowerInvariant(); + var cleanedPath = UriHelpers.GetCleanUriPath(absolutePath); + string resourceUrl = (cleanedPath ?? "/").ToLowerInvariant(); return $"{httpMethod} {resourceUrl}"; } diff --git a/tracer/test/Datadog.Trace.Tests/PlatformHelpers/AspNetCoreHttpRequestHandlerTests.cs b/tracer/test/Datadog.Trace.Tests/PlatformHelpers/AspNetCoreHttpRequestHandlerTests.cs index 91f41e9d8195..0ef19191950a 100644 --- a/tracer/test/Datadog.Trace.Tests/PlatformHelpers/AspNetCoreHttpRequestHandlerTests.cs +++ b/tracer/test/Datadog.Trace.Tests/PlatformHelpers/AspNetCoreHttpRequestHandlerTests.cs @@ -5,6 +5,8 @@ #if !NETFRAMEWORK using Datadog.Trace.PlatformHelpers; +using Datadog.Trace.Configuration; +using Datadog.Trace.Logging; using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; @@ -16,6 +18,19 @@ public class AspNetCoreHttpRequestHandlerTests { public const string OriginalPath = "/somepath/Home/Index"; + [Fact] + public void GetDefaultResourceName_ReturnsUnknownSlash_WhenRequestIsNull() + { + var handler = new AspNetCoreHttpRequestHandler( + DatadogLogging.GetLoggerFor(), + "aspnet_core.request", + IntegrationId.AspNetCore); + + var result = handler.GetDefaultResourceName(null); + + result.Should().Be("UNKNOWN /"); + } + [Theory] [InlineData(null, "/somepath/Home/Index")] [InlineData("", "/somepath/Home/Index")]