12

How would I add EmployeeId and DesignationId to an object and then retrieve it from Session state afterward?

Here is my login controller Code:

DataTable dt = sql.GetDataTable("select * from EmpDetails where EmailId = '" + EmailId + "'");
string strempstatus = dt.Rows[0]["Status"].ToString();
string EmpStatus = strempstatus.TrimEnd();

//Models.UserDetails detail = new Models.UserDetails();

if (EmpStatus == "Verified")
{
    //i want to create object which store below two variable value
    string EmployeeId = dt.Rows[0]["Id"].ToString();
    string DesignationId = dt.Rows[0]["D_Id"].ToString();

    //I want to stored object in below session
    HttpContext.Session.SetString("EmployeeData", EmployeeId);

    HttpContext.Session.SetInt32("EmployeeID", Convert.ToInt32(EmployeeId));
    //For Destroy Session
    //HttpContext.Session.Remove("EmployeeID");

    Int32? Saved = HttpContext.Session.GetInt32("EmployeeID");

    if (DesignationId == "1")
    {
        return RedirectToAction("Index", "AdminDashboard");
    }
    else
    {
        return RedirectToAction("Index", "UserDashboard");
    }
}
Jason Shave
  • 2,462
  • 2
  • 29
  • 47
Bhautik Kukadiya
  • 133
  • 1
  • 1
  • 7
  • Please post the code of `ConfigureServices()` method in your question. Did you get any error? – Krishnraj Rana Mar 18 '19 at 12:05
  • No, I didn't get any error but I want to know how to store above two variable"EmployeeId and DesignationId" values in object and after that how to store that object in session and get values back by casting session??? – Bhautik Kukadiya Mar 19 '19 at 05:26

1 Answers1

35

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

In order to store complex objects in your session in .NET Core, follow the following steps:

Create a model class of your object type (in your case EmployeeDetails):

public class EmployeeDetails
{
    public string EmployeeId { get; set; }
    public string DesignationId { 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);
   }
}

Then finally set the complex object in your session as:

var employee = new EmployeeDetails();
employee.EmployeeId = "1";
employee.DesignationId = "2";

HttpContext.Session.SetObjectAsJson("EmployeeDetails", employee);

To retrieve your complex object in your session:

var employeeDetails = HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
int employeeID = Convert.ToInt32(employeeDetails.EmployeeId);
int designationID= Convert.ToInt32(employeeDetails.DesignationId);

EDIT:

I have seen quite a bit of questions where the Session data is not accessible on the View, so I am updating my answer on how to achieve this also. In order to use your Session variable on the View, you need to inject IHttpContextAccessor implementation to your View and use it to get the Session object as required:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
    //Get object from session
    var mySessionObject = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
 }

<h1>@mySessionObject.EmployeeId</h1>
<h1>@mySessionObject.DesignationId</h1>
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • I already knew it how to create session and retrieve but the issue is how to store above two variable"EmployeeId and DesignationId" values in object and after that how to store that object in session and get values back by casting session??? – Bhautik Kukadiya Mar 19 '19 at 05:25
  • it can used like this https://stackoverflow.com/a/62019854/3328167 instead of extension method – PrashSE Jan 19 '22 at 10:11
  • how to use session in asp.net core there is only Program.cs file and no Startup file, I need to store user_name in session , in MVC before I used Session["UserName"] = user.FirstOrDefault().user_name; which retreived from the db ? – Abdullah Dec 04 '22 at 11:35
  • @Abdullah What type of project is yours? `Session` is not supported in some types of projects like Console applications. If you are doing web based application, then it will make sense to use `Session` variables – Rahul Sharma Dec 04 '22 at 13:33
  • 1
    yes I am using visual studio 2022 and no startup file in new projects , I will create asp.net core web application , I tried a solution and put the code in Program.cs builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(); app.UseSession(); also installed the NuGet package Microsoft.AspNetCore.Session finally to store the user_name value at login i used this code HttpContext.Session.SetString("UserName", userDetails.FirstOrDefault().UserName); in login controller and I will try it thank you – Abdullah Dec 05 '22 at 05:49