Ratchanon Volty
Ratchanon Volty

Reputation: 41

ASP.NET Core - How to assign a dictionary value to a session

How to assign a dictionary value to a session in ASP.NET Core?

I getting an error:

Cannot convert from Dictionary<string, bool> to string

//Role
var query2 = (from a in _db.MuRole
    select new { a.RoleName, a.RolePiority }).ToList();

var lvRole = "";
Dictionary<string, bool> dicRole = new Dictionary<string, bool>();
foreach (var item in query2)
{
    lvRole = item.RoleName;
    //bool status = function check();
    dicRole.Add(item.RoleName, false);
}

HttpContext.Session.SetString("Role", dicRole);

Upvotes: 0

Views: 796

Answers (1)

Yong Shun
Yong Shun

Reputation: 51420

SessionExtensions.SetString(ISession, String, String) Method only supported provided value with string type only.

To store an object in Session, you need to serialize the object (To write JSON to a string or to a file).

If you install Newtonsoft.Json library,

using Newtonsoft.Json;

HttpContext.Session.SetString("Role", JsonConvert.SerializeObject(dicRole));

Or using the default JsonSerializer.

using System.Text.Json;

HttpContext.Session.SetString("Role", JsonSerializer.Serialize(dicRole));

To get the object from the session, you have to deserialize the string.

Upvotes: 2

Related Questions