user442540
user442540

Reputation:

MVC ASP.net session is null

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?

Upvotes: 1

Views: 3404

Answers (3)

manofseven2
manofseven2

Reputation: 51

1) Start–> Administrative Tools –> Services

2) right click over the ASP.NET State Service and click “start”

*additionally you could set the service to automatic so that it will work after a reboot.

For more details you can check my blog post: http://jamshidhashimi.com/2011/03/16/unable-to-make-the-session-state-request-to-the-session-state-server/ ref: Unable to make the session state request to the session state server

Upvotes: 0

user442540
user442540

Reputation:

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

Upvotes: 1

The Moof
The Moof

Reputation: 804

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

Upvotes: 1

Related Questions