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");
}
}
Session is a feature in ASP.NET Core that enables us to save/store the user data. Session stores the data in the dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at cookie. The SessionId cookie is sent with every request.
But, there is way to store complex object in session, we can convert complex object into Json String, then store them in session object using the same SetString function, here is an working example of how we can store complex data in asp.net core session.
The serialize() function in PHP can be used before storing the object, and the unserialize() function can be called when the object needs to be retrieved from the session. The function converts a storable representation of a specific value into a sequence of bits.
It means you need persist your session in database at appropriate point. You may use out of process session storage (database or different server) - you have to mark your shopping cart class as serializable in such case. There is performance cost to out-of-process sessions.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With