diff --git a/src/Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices/SessionState/Serialization/HttpSessionStateBaseWrapper.cs b/src/Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices/SessionState/Serialization/HttpSessionStateBaseWrapper.cs index c06b603016..8a58fe0ef7 100644 --- a/src/Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices/SessionState/Serialization/HttpSessionStateBaseWrapper.cs +++ b/src/Microsoft.AspNetCore.SystemWebAdapters.FrameworkServices/SessionState/Serialization/HttpSessionStateBaseWrapper.cs @@ -54,7 +54,17 @@ public bool IsAbandoned } } - public IEnumerable Keys => State.Keys.Cast(); + public IEnumerable Keys + { + get + { + // If the underlying storage mechanism is SessionStateItemCollection then there can be issues around the enumerator causing side effects. + // There are precautions in the implementation to prevent this, but we have seen an exception around this in practice (see dotnet/systemweb-adapters#556). + // However, there is no simple way to check if this is the case, so we'll preemptively create a copy. + // See https://referencesource.microsoft.com/#System.Web/State/SessionStateItemCollection.cs,435 for the warnings in the implementation. + return [.. State.Keys.Cast()]; + } + } public void Clear() => State.Clear();