1

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;
    }

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

please vote my queston, im trying student badge now .thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.