Best Way to manage session in .NET core centrally.

Create this common class and create 2 method for one session

One method is for set value and second method is used for get value from session.

This is also known as extension method concept in C# .NET.


After creating this class you can simply set and get value from session.


example :


HttpContext.Session.InstitutionId(Id);  -> Here I we are set value in session.

Id =Convert.ToInt32(HttpContext.Session.PortalUserId()) -> here we are getting value from session.



using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Collections.Generic;

using System.Text.Json;

using System.Web;


namespace Z.App.Helper

{

    public static class CentralSession 

    {

        private static string PORTAL_USER_ID = "PortalUserId";

        private static string INSTITUTION_ID = "InstitutionId";

        private static string ISADMIM = "IsAdmin";

        





        public static void PortalUserId(this ISession session, int value)

        {

            session.SetInt32(PORTAL_USER_ID, value);

        }

        public static int? PortalUserId(this ISession session)

        {

            return session.GetInt32(PORTAL_USER_ID);

        }


        public static void IsAdmin(this ISession session, bool value)

        {

            session.SetInt32(ISADMIM, Convert.ToInt32(value));

        }


        public static bool IsAdmin(this ISession session)

        {

            return Convert.ToBoolean(session.Get(ISADMIM));

        }

    }

}


Note : please do comment ... and correct me ...

Thanks in advance....


Comments

Popular posts from this blog

Search Record From Table Using jQuery in Asp.net core MVC

How To insert Radio Button Data in DataBase -- MVC

Toolbox Webparts Controls