Phong Phạm Thanh
Phong Phạm Thanh

Reputation: 11

Using Session In Asp.Net 5.0

I want to use Session in Asp.Net 5.0 Normally I use

HttpContext.Session.GetInt32()

or

HttpContext.Session.GetString()

But now I want to pass an Object to Session and I can't found any Method for that need In previous version Asp.Net can use Session["name"] = object but I can use that for Asp.Net 5.0

How to Pass Object To Session Variable in Asp.Net 5.0

Upvotes: 1

Views: 424

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11110

The ISession api's are designed for scale. You might need to access the same session from multiple web servers, or across restarts.

The core API is based around storing byte arrays. It's up to you what those bytes represent.

With a couple of extension methods, you could store data objects as a UTF8 json;

public static async Task<T> Get<T>(this ISession session, string key)
{
    await session.LoadAsync();
    var bytes = session.Get(key);
    if (bytes == null)
        return default;
    return JsonSerializer.Deserialize<T>(bytes);
}
public static async Task Set<T>(this ISession session, string key, T value)
{
    await session.LoadAsync();
    if (EqualityComparer<T>.Default.Equals(value, default(T)))
        session.Remove(key);
    else
        session.Set(key, JsonSerializer.SerializeToUtf8Bytes(value));
}

Upvotes: 1

Related Questions