0

I am using ASP.NET Core. How can I use session variables in a static method?

In ASP.NET, this looked like this:

protected static string AssignSession()  
{
    return HttpContext.Current.Session["UserName"].ToString();
}

protected void Page_Load(object sender, EventArgs e)
{
    Session["UserName"] = "super user";
}

When I try that in ASP.NET Core, I get the following error:

An object reference is required for the non-static field, method, or property 'ControllerBase.HttpContext'.

poke
  • 369,085
  • 72
  • 557
  • 602
Prakash S
  • 85
  • 8
  • 3
    Possible duplicate of [How can I get the value of a session variable inside a static method?](https://stackoverflow.com/questions/2577183/how-can-i-get-the-value-of-a-session-variable-inside-a-static-method) – SᴇM Jul 02 '19 at 08:39
  • 1
    Sir, i am asking Asp.net-core. – Prakash S Jul 02 '19 at 08:46
  • Try `System.Web.HttpContext.Current.Session[...]` – Lasse V. Karlsen Jul 02 '19 at 08:48
  • 2
    First of all, why use a static method? Second, there's no static HttpContext instance in ASP.NET Core, nor a `Page_Load` event - there are no events at all. [HttpContext](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.razorpages.pagemodel.httpcontext?view=aspnetcore-2.2) is now a property of the controller or PageModel. You'll have [to enable Session](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2) before you can use it too. If you want to access the Session object in another method you'll have to pass it as a parameter – Panagiotis Kanavos Jul 02 '19 at 08:49

1 Answers1

4

The answer is generally: You don’t.

In ASP.NET Core, you pretty much avoid static code. Instead, ASP.NET Core uses dependency injection to make services available as dependencies and to control their lifetime.

A static utility class in ASP.NET would probably translate to a singleton service in ASP.NET Core. Using that is very straightforward; you start by creating a non-static service that does whatever you want to do. Since this is using dependency injection, you can just depend on other services as well:

public class MyService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void SetSomeSessionValue(string value)
    {
        var httpContext = _httpContextAccessor.HttpContext;

        httpContext.Session["example"] = value;
    }
}

You can do whatever you want there. The IHttpContextAccessor is used to retrieve the current HttpContext.

Then, you need to register your service with the dependency injection container. You do that in the ConfigureServices method in your Startup.cs:

services.AddSingleton<MyService>();

// we also add the HttpContextAccessor, in case it wasn’t already (implicitly) registered before
services.AddHttpContextAccessor();

And now, you can depend on this MyService within controllers or other services by simply adding it as a constructor argument:

public class HomeController
{
    private readonly MyService _myService;

    public HomeController(MyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        _myService.SetSomeSessionValue("test");
        return View();
    }
}

Now, you have a non-static service that has clear dependencies and which you can test properly.


That all being said, many constructs already have access to the current HttpContext and as such to the session. For example, in controllers, Razor pages, or even Razor views, you can just access the HttpContext directly as it is an instance variable.

So if you are not building some reusable utility code, you don’t actually need to create a service for this. You could just for example create a (non-static) utility method within your controller that then accesses the HttpContext directly.

poke
  • 369,085
  • 72
  • 557
  • 602