Session Store IQueryable in HttpContext

浪尽此生 提交于 2019-12-07 08:32:24

Okay, so as a basic example on how to setup a complex object in your Session in .NET Core:

First setup your session:

In your Startup.cs, under the Configure method, add the following line:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}

And under the ConfigureServices method, add the following line:

public void ConfigureServices(IServiceCollection services)
{
  //Added for session state
  services.AddDistributedMemoryCache();

  services.AddSession(options =>
  {
  options.IdleTimeout = TimeSpan.FromMinutes(10);               
  });
}

To add complex objects in your list to your Session (Please note that this an example only and not specific to your case since I do not know what PropertyOwnerRoleViewModel definiton is):

Model:

public class EmployeeDetails
{
    public string EmployeeId { get; set; }
    public string DesignationId { get; set; }
}

public class EmployeeDetailsDisplay
{
    public EmployeeDetailsDisplay()
    {
        details = new List<EmployeeDetails>();
    }
    public List<EmployeeDetails> details { get; set; }
}

Then create a SessionExtension helper to set and retrieve your complex object as JSON:

public static class SessionExtensions
        {
            public static void SetObjectAsJson(this ISession session, string key, object value)
            {
                session.SetString(key, JsonConvert.SerializeObject(value));
            }

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

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

Adding this complex object to your session:

 //Create complex object
 var employee = new EmployeeDetailsDisplay();

 employee.details.Add(new EmployeeDetails
 {
 EmployeeId = "1",
 DesignationId = "2"
 });

 employee.details.Add(new EmployeeDetails
 {
 EmployeeId = "3",
 DesignationId = "4"
 });
//Add to your session
HttpContext.Session.SetObjectAsJson("EmployeeDetails", employee);

And finally to retrieve your complex objects from your Session:

var employeeDetails = HttpContext.Session.GetObjectFromJson<EmployeeDetailsDisplay>("EmployeeDetails");

//Get list of all employee id's
List<int> employeeID = employeeDetails.details.Select(x => Convert.ToInt32(x.EmployeeId)).ToList();
//Get list of all designation id's
List<int> designationID= employeeDetails.details.Select(x=> Convert.ToInt32(x.DesignationId)).ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!