Home > Software design >  How to getting, setting Object value session in .net core 2
How to getting, setting Object value session in .net core 2

Time:07-29

I want gettting,settting object value to ISession in .net core c#.

set string value :

ht.SetString(key, "string")

but how to get and set object value?

My code is below

Cannot convert from object to string

    public void SetSession(string key, object value)
    {
        ISession ht = this.GetSessionHt();
        ht.SetString(key, (object)value);
    }



    public T GetSession<T>(string key)
    {
        ISession ht = this.GetSessionHt();

        if (ht.GetString(key)!=null)
        {
            return (T)ht.GetString(key);
        }
        return default(T);
    }

    private ISession GetSessionHt()
    {
        ISession session = HttpContext.Session;
        return session;
    }

CodePudding user response:

You can use SerializeObject and DeserializeObject<T> to achieve it.

Create an extension method on session:

public static class TestSession
    {
        //set session
        public static void SetObjectsession(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        //get session
        public static T GetObjectsession<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

Then you can just use it in your code:

Person p = new Person()
            {
                Id = 1,
                Name = "AAA"
            };

 HttpContext.Session.SetObjectsession("A", p);

 var result = HttpContext.Session.GetObjectsession<Person>("A");
  • Related