How to access the Session in ASP.NET Core via static variable?

Navaneeth

In earlier version of Asp.Net session can be accessed in any page like a static variable using

System.Web.HttpContext.Current.Session["key"]

In Asp.Net Core, How to access session in different class called via controller, without passing the session property as an additional parameter in the constructor of all classes

Ron C

Revised approach 1/17/17 to fix bug

First, I'll assume that you have your ASP.NET Core application configured to use session state. If not see @slfan's answer How to access the Session in ASP.NET Core via static variable?

How to access session in different class called via controller, without passing the session property as an additional parameter in the constructor of all classes

Asp.Net Core is designed around dependency injection and in general the designers didn't provide much static access to context information. More specifically there is no equivalent to System.Web.HttpContext.Current.

In Controllers you can get access to Session vars via this.HttpContext.Session but you specifically asked how to get access to the session from methods called by the controller without passing the session property as a parameter.

So, to do this we need to setup our own static class to provide access to session and we need some code to initialize that class at startup. Since it's likely that a person may want static access to the whole HttpContext object and not just the Session I took that approach.

So first we need the static class:

using Microsoft.AspNetCore.Http; 
using System;
using System.Threading;

namespace App.Web {

    public static class AppHttpContext {
        static IServiceProvider services = null;

        /// <summary>
        /// Provides static access to the framework's services provider
        /// </summary>
        public static IServiceProvider Services {
            get { return services; }
            set {
                if(services != null) {
                    throw new Exception("Can't set once a value has already been set.");
                }
                services = value;
            }
        }

        /// <summary>
        /// Provides static access to the current HttpContext
        /// </summary>
        public static HttpContext Current {
            get {
                IHttpContextAccessor httpContextAccessor = services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
                return httpContextAccessor?.HttpContext;
            }
        } 

    }
}

Next we need to add a service to the DI container that can provide access to the current HttpContext. This service ships with the Core MVC framework but is not installed by default. So we need to "install" it with a single line of code. This line goes in the ConfigureServices method of the Startup.cs file and can be located anywhere in that method:

//Add service for accessing current HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();    

Next we need to setup our static class so that it has access to the DI container to obtain the service we just installed. The code below goes in the Configure method of the Startup.cs file. This line can be be located anywhere in that method:

AppHttpContext.Services = app.ApplicationServices; 

Now any method called by the Controller, even via the async await pattern, can access the current HttpContext via AppHttpContext.Current

So, if we use the Session extension methods in the Microsoft.AspNetCore.Http namespace, we can save an int called "Count" to session could be done like this:

AppHttpContext.Current.Session.SetInt32("Count", count);

And retrieving an int called "Count" from session could be done like this:

int count count = AppHttpContext.Current.Session.GetInt32("Count");

Enjoy.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to access session from a view in ASP .NET Core MVC 1.0

From Dev

How to access cookie asp.net core

From Dev

How to transfer session variable from classic asp to asp.net?

From Dev

How to access Session Timeout value in Asp.Net Core MVC 1.0 (aka MVC 6 RC1)?

From Dev

How to access ASP classic session variable from PHP?

From Dev

How to access session in class library .Net Core 5

From Dev

Is it safe to store and update list in asp.net session via static methods?

From Dev

ASP NET Core MVC - How to configure Out of Process Session State?

From Dev

How to save object to session in ASP.NET & access it in View

From Dev

how can I access Session in preinit function in asp.net?

From Dev

How can pass a data context to a static method in Asp .Net Core

From Dev

How to modify the session variable inside the asp.net webmethod

From Dev

How to instantiate an ASP.net (MVC 5) Session Variable?

From Dev

How to access Program Files folder via ASP.NET MVC

From Dev

How to access session variable in layout

From Dev

How to implement Permission Based Access Control with Asp.Net Core

From Dev

How to access Asp.net Core DI Container from Class

From Dev

ASP.NET Core MVC dropdown list on _layout page to a Session variable

From Dev

ASP.NET Core clear session issue

From Dev

ASP.NET ternary operator on the Session variable

From Dev

ASP.NET ternary operator on the Session variable

From Dev

How I can access a private static member variable via the class constructor?

From Dev

Meteor: How to filter data via a session variable

From Dev

Static class to access Session

From Dev

Session State SQLServer deleting static variables in asp.net

From Dev

ASP.NET 5 (Core): How to store objects in session-cache (ISession)?

From Java

Access the current HttpContext in ASP.NET Core

From Dev

Access Denied in Asp .Net Core by Claims Authorization

From Dev

How to use DI inside a static Method in Asp.net Core rc1

Related Related

  1. 1

    How to access session from a view in ASP .NET Core MVC 1.0

  2. 2

    How to access cookie asp.net core

  3. 3

    How to transfer session variable from classic asp to asp.net?

  4. 4

    How to access Session Timeout value in Asp.Net Core MVC 1.0 (aka MVC 6 RC1)?

  5. 5

    How to access ASP classic session variable from PHP?

  6. 6

    How to access session in class library .Net Core 5

  7. 7

    Is it safe to store and update list in asp.net session via static methods?

  8. 8

    ASP NET Core MVC - How to configure Out of Process Session State?

  9. 9

    How to save object to session in ASP.NET & access it in View

  10. 10

    how can I access Session in preinit function in asp.net?

  11. 11

    How can pass a data context to a static method in Asp .Net Core

  12. 12

    How to modify the session variable inside the asp.net webmethod

  13. 13

    How to instantiate an ASP.net (MVC 5) Session Variable?

  14. 14

    How to access Program Files folder via ASP.NET MVC

  15. 15

    How to access session variable in layout

  16. 16

    How to implement Permission Based Access Control with Asp.Net Core

  17. 17

    How to access Asp.net Core DI Container from Class

  18. 18

    ASP.NET Core MVC dropdown list on _layout page to a Session variable

  19. 19

    ASP.NET Core clear session issue

  20. 20

    ASP.NET ternary operator on the Session variable

  21. 21

    ASP.NET ternary operator on the Session variable

  22. 22

    How I can access a private static member variable via the class constructor?

  23. 23

    Meteor: How to filter data via a session variable

  24. 24

    Static class to access Session

  25. 25

    Session State SQLServer deleting static variables in asp.net

  26. 26

    ASP.NET 5 (Core): How to store objects in session-cache (ISession)?

  27. 27

    Access the current HttpContext in ASP.NET Core

  28. 28

    Access Denied in Asp .Net Core by Claims Authorization

  29. 29

    How to use DI inside a static Method in Asp.net Core rc1

HotTag

Archive