Created
November 30, 2012 07:23
-
-
Save lkaczanowski/4174294 to your computer and use it in GitHub Desktop.
Creates HttpContext with Session to stub HttpContext.Current
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Very, very good.
This code saved the day
Tks
God bless
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);