views:

72

answers:

2

I have the following code which was ok until someone else put some other code in the site which sorta mucks it up now.

This is my code:

var existingContext = HttpContext.Current;
var writer = new StringWriter();
var response = new HttpResponse(writer);
var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };
HttpContext.Current = context;
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Default);
HttpContext.Current.Session["Test"] = "test";
for (Int32 i = 0; i < existingContext.Session.Count; i++)
{
    HttpContext.Current.Session.Add(existingContext.Session.Keys[i], existingContext.Session[i]);
}

The idea behind this is to be able to capture the output of a view and render it to pdf. Now my only issue is that when i assign context back to HttpContext.Current, the session is null. I need to be able to initialize the session so that i can assign variables into it.

i will also add that this is inside a static class

public static class ControllerExtensions

Any clues?

A: 

If this is occurring inside of an HttpHandler, you need to add the IRequiresSessionState interface to your handler for the session to be available -

public class HttpPdfWriteHandler : IHttpHandler, IRequiresSessionState {
     [...]
}

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx

The Moof
unfortunately this is occurring inside a static classpublic static class ControllerExtensions
Giles Papworth
i got the original code from: http://www.jimzimmerman.com/blog/2009/10/06/PdfResult+A+Custom+ActionResult+In+ASPNET+MVC.aspxand http://jamesmcc.wordpress.com/2010/06/02/pdfresult-a-custom-actionresult-in-asp-net-mvc2-updated/
Giles Papworth
A: 

I seem to have solved the issue for now and that was to remove the lines:

            var context = new HttpContext(existingContext.Request, response) { User = existingContext.User };
        HttpContext.Current = context;
        HttpContext.Current.Request.
        for (Int32 i = 0; i < existingContext.Session.Count; i++)
        {
            HttpContext.Current.Session.Add(existingContext.Session.Keys[i], existingContext.Session[i]);
        }
Giles Papworth