Click here to Skip to main content
15,886,816 members
Articles / Web Development / ASP.NET / ASP.NETvNext
Tip/Trick

Application and Session State in ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 Jul 2016CPOL2 min read 21.5K   3   1
Application and Session state in ASP.NET Core

Introduction

Managing session and application state is a very common operation in any web based application. In ASP.NET Core 1.0, there is no readymade solution to keep track of application data so far. Anyway, we can implement our own application state and inject in the request pipeline. In this example, we have implemented singleton pattern in the ApplicationVariable class. It has the ReturnOject() function to maintain singleton state.

C#
    public class ApplicationVariable
{
    public  int _count = 0;
    private static ApplicationVariable _ObjApp;
    private readonly RequestDelegate _next;
    public ApplicationVariable(RequestDelegate next)
    {
        _next = next;
    }
    public ApplicationVariable ReturnObject()
    {
        if (_ObjApp == null)
            _ObjApp = new ApplicationVariable(_next);
        return _ObjApp;
    }
    public async Task Invoke(HttpContext httpContext)
    {
        var count = ++ this.ReturnObject()._count;
        httpContext.Response.Headers.Append("Count", count.ToString());
        await _next.Invoke(httpContext);
    }
}

The invoke function takes the current context as a parameter and helps by making the class as injectable in HTTP pipeline. The function just increments the value of the _count variable and sets "Count" header to HTTP response with updated _count value. Now, to inject the class in pipeline, we have to call the UseMiddleware<T>() function in Configure section.

C#
public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();
        app.UseMiddleware<ApplicationVariable>();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

If we sniff response header, we will see that the Count header is present in response and in each subsequent request, it’s retaining updated value.

This is our custom solution to implement Application state. How to maintain session state? To maintain session state, we need to add the following package from NuGet.

C#
"Microsoft.AspNet.Session": "1.0.0-rc1-final"

The next step is to call the AddSession() function in the ConfigurationService section.

C#
public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSession();
        services.AddCaching();
    }

Call the UseSession() function in the Configure section.

C#
public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
        app.UseIISPlatformHandler();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Now, we are ready to use session in our controller. HttpContext has Session property which provides a couple of functions to play with session data. In this example, we are using SetString() function to set data in session and GetString() function to get data.

C#
public ActionResult Index()
    {
            //Set value to session
            HttpContext.Session.SetString("Name", "Sourav Kayal");

            //Get Value from Session
            var data = HttpContext.Session.GetString("Name");

            return View();
    }

How to access session data from outside of controller? We can use HttpContextAccessor object to access session variable outside from controller class. Here is an example code for the same:

C#
   public class SessionRapper
{
       private readonly IHttpContextAccessor _httpContextAccessor;
       private ISession _sessionContext => _httpContextAccessor.HttpContext.Session;
       public SessionRapper(IHttpContextAccessor httpContextAccessor)
       {
           _httpContextAccessor = httpContextAccessor;
       }
       public void SetToSession()
       {
           _sessionContext.SetString("Name", "Sourav Kayal");
       }
       public void GetFromSession()
       {
           var data = _sessionContext.GetString("Name");
       }
   }

Conclusion

HttpContext.Session provides a couple of flavored functions like Set(), SetInt32() to store data and Get(), GetInt32(), GetString(), TryGetValue() to get value from session.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
QuestionApplicationVariable Pin
Mark Redman24-Jul-16 23:01
Mark Redman24-Jul-16 23:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.