Skip to content

Commit 7644163

Browse files
committed
Add support for mocking Session when accessed via HttpContext.Current
1 parent 10e3a92 commit 7644163

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

src/ServiceStack/Host/AspNet/AspNetRequest.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ public AspNetRequest(HttpContextBase httpContext, string operationName, RequestA
4242
}
4343

4444
this.RequestPreferences = new RequestPreferences(httpContext);
45+
46+
if (httpContext.Items != null && httpContext.Items.Count > 0)
47+
{
48+
foreach (var key in httpContext.Items.Keys)
49+
{
50+
var strKey = key as string;
51+
if (strKey == null) continue;
52+
Items[strKey] = httpContext.Items[key];
53+
}
54+
}
4555
}
4656

4757
public HttpRequestBase HttpRequest

tests/ServiceStack.WebHost.IntegrationTests/Tests/SessionTests.cs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
using System;
2+
using System.Collections.Specialized;
3+
using System.IO;
4+
using System.Web;
5+
using Funq;
26
using NUnit.Framework;
7+
using ServiceStack.Caching;
8+
using ServiceStack.Host.AspNet;
9+
using ServiceStack.Testing;
310

411
namespace ServiceStack.WebHost.IntegrationTests.Tests
512
{
@@ -14,5 +21,28 @@ public void Adhoc()
1421
Console.WriteLine(appliesTo.ToDescription());
1522
Console.WriteLine(string.Join(", ", appliesTo.ToList().ToArray()));
1623
}
17-
}
24+
25+
[Test]
26+
public void Can_mock_Session_when_accessed_via_HttpRequest_Context()
27+
{
28+
using (new BasicAppHost().Init())
29+
{
30+
HttpContext.Current = new HttpContext(
31+
new HttpRequest(null, "http://example.com", null),
32+
new HttpResponse(new StringWriter()));
33+
34+
HttpContext.Current.Items[ServiceExtensions.RequestItemsSessionKey] =
35+
new AuthUserSession {
36+
Id = "mock-session-id",
37+
};
38+
39+
var httpReq = HttpContext.Current.ToRequest();
40+
var session = httpReq.GetSession();
41+
42+
Assert.That(session, Is.Not.Null);
43+
Assert.That(session.Id, Is.EqualTo("mock-session-id"));
44+
}
45+
}
46+
47+
}
1848
}

0 commit comments

Comments
 (0)