Fix rewrite maps not resolved in action URL#65591
Open
kubaflo wants to merge 1 commit intodotnet:mainfrom
Open
Fix rewrite maps not resolved in action URL#65591kubaflo wants to merge 1 commit intodotnet:mainfrom
kubaflo wants to merge 1 commit intodotnet:mainfrom
Conversation
Fixes dotnet#24618 The Pattern.Evaluate() method uses a shared StringBuilder (context.Builder) that gets corrupted when segments recursively call Evaluate() — for example, RewriteMapSegment evaluates an inner Pattern to compute its key. Previously, Evaluate() would Clear() the builder after ToString(), destroying any content appended by the outer call. The fix tracks the startIndex before appending segments, then uses ToString(startIndex, length) and sets Builder.Length = startIndex to restore the builder to its pre-call state. This handles arbitrary nesting depth with zero additional allocations while preserving the shared StringBuilder design. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Contributor
|
Thanks for your PR, @@kubaflo. Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes an IIS URL Rewrite compatibility bug where rewrite maps used inside <action url="..."> could fail due to recursive Pattern.Evaluate() calls corrupting the shared RewriteContext.Builder.
Changes:
- Update
Pattern.Evaluate()to snapshot the sharedStringBuilderlength and restore it after evaluation, making nested/recursive evaluations safe. - Add a regression test covering rewrite map evaluation in an action URL combined with other pattern segments.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| src/Middleware/Rewrite/src/Pattern.cs | Prevents nested Evaluate() calls from clearing/overwriting outer pattern output by restoring builder length to a saved start index. |
| src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs | Adds coverage for rewrite map usage inside an action URL (redirect) to prevent regressions. |
This was referenced Mar 1, 2026
Open
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🤖 AI Summary
🔍 Automated Fix Report
🔍 Pre-Flight — Context & Validation
Issue: #24618 - Rewrite module - Rule action not working with rewrite maps
Area: area-middleware (
src/Middleware/Rewrite/)PR: None — will create
Key Findings
Pattern.Evaluate()is called recursively (e.g.,RewriteMapSegmentevaluates its inner key pattern), the inner call'sClear()wipes the outer call's partial resultTest Command
dotnet test src/Middleware/Rewrite/test/Microsoft.AspNetCore.Rewrite.Tests.csproj🧪 Test — Bug Reproduction
Test Result: ✅ TESTS CREATED
Tests Created:
src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.csInvoke_RewriteMapInActionUrl— verifies rewrite map resolution in redirect action URL🚦 Gate — Test Verification & Regression
Gate Result: ✅ PASSED
All 458 rewrite tests pass with the fix. No regressions.
🔧 Fix — Analysis & Comparison (✅ 3 passed, ❌ 2 failed)
Fix Exploration Summary
Total Attempts: 5
Passing Candidates: 5
Selected Fix: Attempt 0 — Track startIndex in shared StringBuilder
Attempt Results
Cross-Pollination
All 5 approaches converge on the same root cause: recursive
Pattern.Evaluate()calls corrupt the sharedcontext.Builder(StringBuilder on RewriteContext). Models agreed no further alternatives exist.Exhausted: Yes
Comparison
Recommendation
Attempt 0 (startIndex tracking) is the best fix:
✅ Attempt 0: PASS
Attempt 0 — Baseline (claude-opus-4.6-fast)
Approach: Fix Pattern.Evaluate() to track startIndex of StringBuilder instead of Clear()
Changed
context.Builder.Clear()tocontext.Builder.Length = startIndexandcontext.Builder.ToString()tocontext.Builder.ToString(startIndex, length). This correctly handles recursive pattern evaluations.📄 Diff
⚪ Attempt 1: UNKNOWN
Attempt 1: Per-call local StringBuilder
Approach
Instead of using the shared
context.Builder(which gets corrupted on recursivePattern.Evaluatecalls),allocate a new local
StringBuilderon eachPattern.Evaluateinvocation.This eliminates the shared mutable state that caused the corruption when
RewriteMapSegmentevaluatedits inner key pattern (which recursively called
Pattern.Evaluate, clobbering the outer call's builder state).Key change
context.Builder.Append(...)/context.Builder.Clear()with a freshnew StringBuilder(64)context.Builderis no longer touched inPattern.EvaluateResult
PASSED - Failed: 0, Passed: 3, Skipped: 0, Total: 3
📄 Diff
✅ Attempt 2: PASS
Approach (attempt 2)
Make Pattern.Evaluate() re-entrancy safe by only swapping RewriteContext.Builder when it's already in use.
This preserves the outer builder contents and avoids the corruption caused by inner calls clearing the shared builder.
⚪ Attempt 3: UNKNOWN
Alternative approach: remove shared RewriteContext.Builder usage in Pattern.Evaluate and build the final value via string.Concat over per-segment evaluation results.
Implementation: allocate string?[] sized to PatternSegments.Count, fill it in a for-loop with PatternSegments[i].Evaluate(...), then return string.Concat(values).
Why distinct: this avoids shared mutable StringBuilder entirely without tracking indices, per-call StringBuilder creation, or builder swapping.
⚪ Attempt 4: UNKNOWN
Approach: Hybrid Builder/Local String
The issue is that
Pattern.Evaluateuses a sharedcontext.Builderwhich is cleared upon completion. Recursive calls (e.g., viaRewriteMapSegment) trigger nestedPattern.Evaluatecalls that clear the builder, destroying partial results from the outer scope.The fix uses a hybrid strategy:
context.Builder.Length.Length > 0, it implies the builder is in use by an outer scope (recursion). In this case, fall back to simple string concatenation using a local variable. This avoids clearing the shared builder.Length == 0, use the shared builder for efficiency (standard path).This approach avoids allocating a new
StringBuilder(rejected attempt 1) and avoids complex state management (rejected attempt 0), while correctly handling recursion.Results
Evaluate_RecursivePattern_VerifyCorruptionpassed.Pattern.cs.Diff