Skip to content

[HeaderDictionary] Reassign the underlying enumerator after calling reset #61701

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion src/Http/Http/src/HeaderDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,10 @@ void IEnumerator.Reset()
{
if (_notEmpty)
{
((IEnumerator)_dictionaryEnumerator).Reset();
// The cast causes the enumerator to be copied by value so we must cast it back to the original type after resetting.
var enumerator = (IEnumerator)_dictionaryEnumerator;
enumerator.Reset();
_dictionaryEnumerator = (Dictionary<string, StringValues>.Enumerator)enumerator;
}
}
}
Expand Down
36 changes: 36 additions & 0 deletions src/Http/Http/test/HeaderDictionaryTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections;
using Microsoft.AspNetCore.InternalTesting.Tracing;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -132,4 +134,38 @@ public void ReturnsCorrectStringValuesEmptyForMissingHeaders(bool withStore)
IDictionary<string, StringValues> asIDictionary = emptyHeaders;
Assert.Throws<KeyNotFoundException>(() => asIDictionary["Header1"]);
}

[Fact]
public void EnumeratorResetsCorrectly()
{
var headers = new HeaderDictionary(
new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase)
{
{ "Header1", "Value1" },
{ "Header2", "Value2" },
{ "Header3", "Value3" }
});

var enumerator = headers.GetEnumerator();
var initial = enumerator.Current;

Assert.True(enumerator.MoveNext());

var first = enumerator.Current;
var last = enumerator.Current;

while (enumerator.MoveNext())
{
last = enumerator.Current;
}

Assert.NotEqual(first, initial);
Assert.NotEqual(first, last);

((IEnumerator)enumerator).Reset();

Assert.Equal(enumerator.Current, initial);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Current, first);
}
}
Loading