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

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.


To save anyone the digging, for .net core 2.1+:

Add the following to public void ConfigureServices(...) in your Startup.cs:

services.AddHttpContextAccessor();

Use by injecting into your service/etc:

public MyService(IHttpContextAccessor httpContextAccessor) { //... }

Thanks to: https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly


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