zhrgci
zhrgci

Reputation: 686

Session: Cannot convert int to byte[] in ASP.NET Core 3.0 C#

I tried to look up how to use the new way of using sessions in core 3.0.

It goes like: HttpContext.Session.Set("UserID", ???);, except I can't fill in an int.

I tried to look it up on the official microsoft site, but that one only had HttpContext.Session.SetInt32 or HttpContext.Session.SetString.

How do you use the new set from core 3.0?

Upvotes: 1

Views: 2344

Answers (2)

Achal Parikh
Achal Parikh

Reputation: 127

I faced the same issue, I was able to resolve it like following we need to convert the value of the session variable to byte - array if in case we need to use httpcontext.Session.Set("variable_name", corresponding bytearray of the value) :

public void func(HttpContext httpcontext)
{
          string emailstring = "xyz.com";
          byte[] bytearray= Encoding.ASCII.GetBytes(emailstring)
          httpcontext.Session.Set("email", bytearray);
}

Upvotes: 1

user1672994
user1672994

Reputation: 10849

The Microsoft.AspNetCore.Http only provides HttpContext.Session.SetInt32 or HttpContext.Session.SetString. Check the documentation at here.

You can use the following extension methods to set and get any primitive and reference type objects:

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T Get<T>(this ISession session, string key)
    {
        var value = session.GetString(key);

        return value == null ? default(T) : 
            JsonConvert.DeserializeObject<T>(value);
    }
}

You can use your choice of Serialization technique like System.Text.Json or BinaryFormatter e.t.c in above extension methods. Check about these extensions method at here.

Now to use

byte[] bytes = ....
HttpContext.Session.Set<byte[]>(SessionKey, bytes);

byte[] newBytes = HttpContext.Session.Get<byte[]>(SessionKey);

Upvotes: 0

Related Questions