How to access HttpContext outside of controllers in ASP.NET MVC?

Viewed 21453

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
        }
    }
4 Answers

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.

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

In .Net core the best way to access HTTPContext outside the controller is to use IHttpContextAccessor. Using DI we can access for example User/HttpContext objects like _httpContextAccessor.HttpContext.User and _httpContextAccessor.HttpContext.HttpContext. For detailed answer please refer this link. Thanks!

Related