Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates HttpContext with Session to stub HttpContext.Current
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using NUnit.Framework;
namespace Mvc.Tests
{
[TestFixture]
public class HttpContextCurrentTests
{
private HttpSessionState _sessionState;
[SetUp]
public void SetUp()
{
HttpContext.Current = CreateHttpContextCurrent();
_sessionState = HttpContext.Current.Session;
}
private HttpContext CreateHttpContextCurrent()
{
var httpRequest = new HttpRequest(string.Empty, "http://someurl/", string.Empty);
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer(
"id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null).Invoke(new object[] { sessionContainer });
return httpContext;
}
}
}
@CShelton11

This comment has been minimized.

Copy link

@CShelton11 CShelton11 commented Feb 28, 2018

This is perfect for cloning http context with session state so subsequent threads can have access to session variables as well as the context properties...

private System.Web.HttpContext CloneContext()
{
var request = System.Web.HttpContext.Current.Request;
var response = System.Web.HttpContext.Current.Response;
var context = new System.Web.HttpContext(request, response);

        var session = System.Web.HttpContext.Current.Session;
        var container = new HttpSessionStateContainer(
            "id",
            new SessionStateItemCollection(),
            new HttpStaticObjectsCollection(),
            60,
            true,
            HttpCookieMode.AutoDetect,
            SessionStateMode.InProc,
            false
        );

        context.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
            BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            CallingConventions.Standard,
            new[] { typeof(HttpSessionStateContainer) },
            null).Invoke(new object[] { container }
        );

        foreach (String key in session.Contents) { context.Session.Add(key, session[key]); }
        return context;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.