Skip to content

Fix GenerateMarkerKey to handle string keys properly in Blazor SSR #62814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
27 changes: 27 additions & 0 deletions src/Components/Endpoints/test/SSRRenderModeBoundaryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,33 @@ public Task SetParametersAsync(ParameterView parameters)
=> throw new NotImplementedException();
}

public static IEnumerable<object[]> 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 { }
Expand Down
Loading