diff --git a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs index 5c931c61b6f5..e9930ea24991 100644 --- a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs +++ b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs @@ -212,7 +212,12 @@ private ComponentMarkerKey GenerateMarkerKey(int sequence, object? componentKey) var sequenceString = sequence.ToString(CultureInfo.InvariantCulture); var locationHash = $"{componentTypeNameHash}:{sequenceString}"; - var formattedComponentKey = (componentKey as IFormattable)?.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty; + var formattedComponentKey = componentKey switch + { + string str => str, + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => string.Empty + }; return new() { diff --git a/src/Components/Endpoints/test/SSRRenderModeBoundaryTest.cs b/src/Components/Endpoints/test/SSRRenderModeBoundaryTest.cs index a5db11e45c06..f521373db15f 100644 --- a/src/Components/Endpoints/test/SSRRenderModeBoundaryTest.cs +++ b/src/Components/Endpoints/test/SSRRenderModeBoundaryTest.cs @@ -96,6 +96,33 @@ public Task SetParametersAsync(ParameterView parameters) => throw new NotImplementedException(); } + public static IEnumerable ComponentKeyTestData() + { + yield return new object[] { "test-string-key", "test-string-key" }; + yield return new object[] { 42, "42" }; + yield return new object[] { Guid.Parse("12345678-1234-1234-1234-123456789012"), "12345678-1234-1234-1234-123456789012" }; + yield return new object[] { 123.45, "123.45" }; + yield return new object[] { new DateTime(2023, 12, 25, 10, 30, 0, DateTimeKind.Utc), "12/25/2023 10:30:00" }; + yield return new object[] { null, string.Empty }; + yield return new object[] { new object(), string.Empty }; + } + + [Theory] + [MemberData(nameof(ComponentKeyTestData))] + public void GetComponentMarkerKey_WorksWithVariousKeyTypes(object componentKey, string expectedFormattedKey) + { + // Arrange + var httpContext = new DefaultHttpContext(); + var boundary = new SSRRenderModeBoundary(httpContext, typeof(TestComponent), new InteractiveServerRenderMode()); + + // Act + var markerKey = boundary.GetComponentMarkerKey(1, componentKey); + + // Assert + Assert.Equal(expectedFormattedKey, markerKey.FormattedComponentKey); + Assert.NotEmpty(markerKey.LocationHash); + } + class ServerRenderModeSubclass : InteractiveServerRenderMode { } class WebAssemblyRenderModeSubclass : InteractiveWebAssemblyRenderMode { } class AutoRenderModeSubclass : InteractiveAutoRenderMode { }