Repository navigation
Include parameter default value in RDG endpoint comparison - #69752
Conversation
Endpoints whose handlers differ only by a parameter's default value (for example (int page = 1) and (int page = 2)) were treated as equal and grouped under a single interceptor. The interceptor casts the handler to the first endpoint's delegate type, so the second endpoint threw an InvalidCastException at startup. Compare HasDefaultValue and DefaultValue in EndpointParameter.Equals and GetHashCode so these endpoints get separate interceptors. Fixes dotnet#69675
|
Thanks for your PR, @AnsElgyarDev. Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
@dotnet-policy-service agree |
AdCodicem
left a comment
There was a problem hiding this comment.
I filed #69675 and tried this branch at @AnsElgyarDev's request; the results against the repro are in the issue (#69675 (comment)). I am the reporter, not a maintainer, so these are notes, and none of them is blocking.
On this branch, the new test fails without the change to EndpointParameter.cs with the exception of the issue (its CompileTimeCreationTests variant) and passes with it, and Microsoft.AspNetCore.Http.Generators.Tests is 1658/1658 here too.
On the backport sentence of the description. The change to EndpointParameter.cs applies cleanly to release/11.0. On release/10.0 it would not be enough: #67591 is not in that branch, and endpoints are grouped there through a separate SignatureEquals, not through Equals (EndpointParameter.cs#L604-L611, called from Endpoint.cs#L125-L131):
// release/10.0
public bool SignatureEquals(object obj) =>
obj is EndpointParameter other &&
SymbolEqualityComparer.IncludeNullability.Equals(other.Type, Type) &&
other.SymbolName == SymbolName &&
other.KeyedServiceKey == KeyedServiceKey;Equals and GetHashCode could take these four lines there and (int page = 1) and (int page = 2) would still share an interceptor. Also, #69676 is my request to backport #67591, still open, rather than a backport.
Testing assisted by Claude (Anthropic); I reviewed the results.
| other.LookupName == LookupName && | ||
| other.Ordinal == Ordinal && | ||
| other.IsOptional == IsOptional && | ||
| other.HasDefaultValue == HasDefaultValue && |
There was a problem hiding this comment.
A note rather than a request: as far as I can tell, this line never decides anything, because DefaultValue already says whether there is a default. GetDefaultValueString returns the bare null only for a parameter without one, and writes an explicit null as default:
(int? p) // DefaultValue: null (no default)
(int? p = null) // DefaultValue: default
(string? s = null) // DefaultValue: default
(string s = "null") // DefaultValue: "null" (quoted)I checked it by building the generator without the two HasDefaultValue lines: on 175 Map calls, pairs like the first two above included, the generated file was byte-identical to this branch's. The line is harmless and reads well next to IsOptional, so keeping it is fine; it only means that no test can tell it from its absence.
| other.Ordinal == Ordinal && | ||
| other.IsOptional == IsOptional && | ||
| other.HasDefaultValue == HasDefaultValue && | ||
| other.DefaultValue == DefaultValue && |
There was a problem hiding this comment.
One arrangement that works today stops working with this line. It is contrived, and the real defect is older than this PR, but it is a change of behaviour, so it seems worth knowing:
static string B(int? p = null) => $"b {p ?? -1}";
app.MapGet("/a", (int? p) => $"a {p ?? -1}");
app.MapGet("/b", (Func<int?, string>)B);Before, /a and /b compare equal and share one interceptor, whose cast to Func<int?, string> happens to fit both handlers. After, /b gets its own interceptor, whose cast type is rebuilt from the method (arg0 = default, an anonymous delegate type), while the handler passed is a Func:
System.InvalidCastException : Unable to cast object of type 'System.Func`2[System.Nullable`1[System.Int32],System.String]' to type '<>f__AnonymousDelegate0`2[System.Nullable`1[System.Int32],System.String]'.
Written as a test next to yours, with these three lines as its source, it passes at the base of this PR and fails at its head (CompileTimeCreationTests). /b alone already throws the same way with the 11.0 RC1 generator: the cause is that the cast is rebuilt from the method rather than from the delegate passed, which this PR only stops hiding. I filed it as #69755.
| // Otherwise, the second endpoint reuses the first endpoint's delegate type and default. | ||
| var source = """ |
There was a problem hiding this comment.
The other shape of the same bug is a default against no default. This PR fixes it too, but the test does not cover it:
[Fact]
public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValuePresence()
{
// Same parameter, with and without a default value: the handlers have different delegate types.
var source = """
app.MapGet("/a", (int? page) => $"a {page ?? -1}");
app.MapGet("/b", (int? page = null) => $"b {page ?? -1}");
""";
var (_, compilation) = await RunGeneratorAsync(source);
var endpoints = GetEndpointsFromCompilation(compilation);
Assert.Equal(2, endpoints.Length);
var httpContextA = CreateHttpContext();
await endpoints[0].RequestDelegate(httpContextA);
await VerifyResponseBodyAsync(httpContextA, "a -1");
var httpContextB = CreateHttpContext();
await endpoints[1].RequestDelegate(httpContextB);
await VerifyResponseBodyAsync(httpContextB, "b -1");
}I ran it on this branch. Without the change to EndpointParameter.cs, its CompileTimeCreationTests variant fails with InvalidCastException (<>f__AnonymousDelegate02[System.Nullable1[System.Int32],System.String] to System.Func2[System.Nullable1[System.Int32],System.String]); with the change it passes.
| } | ||
|
|
||
| [Fact] | ||
| public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValue() |
There was a problem hiding this comment.
The bug is not always an exception, which may be worth a test of its own, since it does not go through the cast. 1.0m and 1.00m are equal constants, so both lambdas get the same delegate type and nothing throws; the second endpoint simply answers with the first one's default:
[Fact]
public async Task MapAction_QueryParam_SharedDelegateSignature_PreservesDecimalDefaultScale()
{
// 1.0m and 1.00m are equal constants, so both lambdas have the same delegate type and nothing throws:
// only the fallback value tells the two endpoints apart.
var source = """
app.MapGet("/a", (decimal rate = 1.0m) => rate.ToString(System.Globalization.CultureInfo.InvariantCulture));
app.MapGet("/b", (decimal rate = 1.00m) => rate.ToString(System.Globalization.CultureInfo.InvariantCulture));
""";
var (_, compilation) = await RunGeneratorAsync(source);
var endpoints = GetEndpointsFromCompilation(compilation);
Assert.Equal(2, endpoints.Length);
var httpContextA = CreateHttpContext();
await endpoints[0].RequestDelegate(httpContextA);
await VerifyResponseBodyAsync(httpContextA, "1.0");
var httpContextB = CreateHttpContext();
await endpoints[1].RequestDelegate(httpContextB);
await VerifyResponseBodyAsync(httpContextB, "1.00");
}I ran it on this branch as well. Without the change to EndpointParameter.cs, its CompileTimeCreationTests variant fails on the last assertion (Expected: "1.00", Actual: "1.0"); with the change it passes.
|
Thanks @AdCodicem for testing this so thoroughly and for the notes. I've corrected the backport sentence in the description. I'm keeping the |
There was a problem hiding this comment.
🟢 Approval recommended
The focused equality fix matches generated delegate semantics and has faithful regression coverage.
0 open findings
What changed in this PR
Ensures RDG endpoint grouping distinguishes handlers with different parameter defaults, preventing incompatible delegate reuse.
Changes:
- Adds default-value presence and value to parameter equality and hashing.
- Adds regression coverage for endpoints with differing defaults.
| File | Description |
|---|---|
EndpointParameter.cs |
Includes parameter defaults in endpoint comparison keys. |
RequestDelegateCreationTests.QueryParameters.cs |
Verifies each endpoint preserves its own default. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
|
Hi @Youssef1313, thanks for the review and approval! Just checking in: is there anything else needed from my side before this can be merged? Also, it looks like 3 workflows are still awaiting maintainer approval. Happy to make any changes if needed. |
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |
|
After close/reopen, the only failures are the known-flaky Blazor E2E tests (aspnetcore-components-e2e), unrelated to this change. All other checks pass and this has 2 approvals. Could someone re-run the failed jobs or let me know if anything else is needed on my side? |
|
/azp run aspnetcore-components-e2e |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
The only failing test is |
|
/ba-g unrelated failure. |
|
✅ No documentation PR was created. Confidence that documentation is needed: 5% No docs needed: internal bug fix to RDG endpoint grouping so endpoints differing only by parameter default values work correctly. Documentation surfaces considered
|
Include parameter default value in RDG endpoint comparison
Endpoints that differ only by a parameter's default value are no longer grouped under one interceptor.
Description
Endpoints such as
(int page = 1)and(int page = 2)were treated as equal and grouped under a single interceptor. The interceptor casts the handler to the first lambda's delegate type, so the second endpoint threwInvalidCastExceptionat startup.EndpointParameter.EqualsandGetHashCodedid not includeHasDefaultValueandDefaultValue, although the emitted code depends on them (theCastdelegate type captures default values). This PR includes both in the comparison.Tests
Added
MapAction_QueryParam_SharedDelegateSignature_PreservesDefaultValue, which maps two endpoints differing only by default value and verifies each returns its own default (page 1/page 2).InvalidCastExceptiondescribed in the issue.Microsoft.AspNetCore.Http.Generators.Tests, 1658 tests) pass locally, including after rebasing on the latestmain.Note on the backport: on release/10.0 this change would not be enough on its own, since endpoints are grouped there through a separate
SignatureEqualsrather thanEquals/GetHashCode. #69676 is a request to backport #67591, still open. Happy to look at a release/10.0 change if the team wants one.AI assistance: I used Claude (Anthropic) to help analyze the issue and to review and draft the change and test. I reviewed the code and ran all the tests locally.
Fixes #69675