Skip to content

Instantly share code, notes, and snippets.

@lkaczanowski
Created November 30, 2012 07:23
Show Gist options
  • Save lkaczanowski/4174294 to your computer and use it in GitHub Desktop.
Save lkaczanowski/4174294 to your computer and use it in GitHub Desktop.
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
Copy link

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;
    }

@contatoaugusto
Copy link

contatoaugusto commented Mar 10, 2021

Very, very good.
This code saved the day
Tks

@drozdik-m
Copy link

God bless

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment