Skip to content

Commit 02e16b7

Browse files
StephenMolloyrobs
andauthored
Added GetDeterministicHashCode and changed the session id suffix to use that instead of GetHashCode. (#114)
Co-authored-by: Rob Symonds <[email protected]>
1 parent b63deeb commit 02e16b7

3 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/SqlSessionStateProviderAsync/Microsoft.AspNet.SessionState.SqlSessionStateProviderAsync.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
<Compile Include="SqlFxCompatSessionStateRepository.cs" />
7878
<Compile Include="SqlSessionStateRepository.cs" />
7979
<Compile Include="SqlSessionStateRepositoryUtil.cs" />
80+
<Compile Include="StringExtensions.cs" />
8081
</ItemGroup>
8182
<ItemGroup>
8283
<EmbeddedResource Include="Resources\SR.resx">

src/SqlSessionStateProviderAsync/SqlSessionStateProviderAsync.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ internal void Initialize(string name, NameValueCollection config, SessionStateSe
125125

126126
var appId = AppId ?? HttpRuntime.AppDomainAppId;
127127
Debug.Assert(appId != null);
128-
s_appSuffix = appId.GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
128+
s_appSuffix = appId.GetDeterministicHashCode().ToString("X8", CultureInfo.InvariantCulture);
129129

130130
s_oneTimeInited = true;
131131
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
namespace Microsoft.AspNet.SessionState
2+
{
3+
internal static class StringExtensions
4+
{
5+
//============================================================================ robs ==
6+
// This is to replace the call to GetHashCode() when appending AppId to the session id.
7+
// Using GetHashCode() is not deterministic and can cause problems when used externally (e.g in SQL)
8+
// Credit: https://andrewlock.net/why-is-string-gethashcode-different-each-time-i-run-my-program-in-net-core/
9+
//====================================================================== 2023-07-21 ==
10+
internal static int GetDeterministicHashCode(this string str)
11+
{
12+
unchecked
13+
{
14+
int hash1 = (5381 << 16) + 5381;
15+
int hash2 = hash1;
16+
17+
for (int i = 0; i < str.Length; i += 2)
18+
{
19+
hash1 = ((hash1 << 5) + hash1) ^ str[i];
20+
if (i == str.Length - 1)
21+
break;
22+
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
23+
}
24+
25+
return hash1 + (hash2 * 1566083941);
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)