views:

153

answers:

2

Specifically, Session variables. I have an .ashx in my ASP.NET MVC project that is pulling some image data to display to a user, and I need to be able to access an object that I've stored in the session. From controllers I can pull the object fine, but in my ashx page, the context.Session is null. Any thoughts? Thanks!

Here is an example of what I'm trying to do... context.Session is always returning null.

  private byte[] getIconData(string icon)
    {
        //returns the icon file
        HttpContext context = HttpContext.Current;

        byte[] buffer = null;

        //get icon data
        if ( context.Session["tokens"] != null)
        {
            //do some stuff to get icon data
        }
    }
A: 

You must import the System.Web assembly in your code and then you can do something like this:

HttpContext context = HttpContext.Current;

return (User)context.Session["User"];

Editing:

Dude, I did some tests here and it works for me, try something like this:

Create a helper class to encapsulate you getting session variables stuff, it must import the System.Web assembly:

public class TextService
    {
        public static string Message { 
            get 
            { 
                HttpContext context = HttpContext.Current; 
                return (string)context.Session["msg"]; 
            }
            set
            {
                HttpContext context = HttpContext.Current;
                context.Session["msg"] = value;
            }
        }
    }

Then in your controller you should do something like:

TextService.Message = "testing the whole thing";
return Redirect("/home/testing.myapp");

And in your other classes you can call the helper class:

return TextService.Message;

Give it a try.

Alaor
It's still saying that the Session is null, despite being able to access several different session variables in a controller.
Arthurdent510
You have created the session variable? Can you show some code here?
Alaor
Where do you set the Session["tokens"] variable?
Alaor
I set the Session["tokens"] variable inside of one of my MVC controllers. I have the problem when I try to read it from anything outside of that controller.... in this case specifically it's an .ashx file.
Arthurdent510
A: 

Ok, so what I ended up having to do.... in my ashx file, I added in the IReadOnlySessionState interface and it will access the session state just fine. So it looks something like this...

  public class getIcon : IHttpHandler, IReadOnlySessionState
Arthurdent510