i have a basic razor project where i am trying to create a login page.
i have a problem with storing the current user information. In this class i have this code:
public User currentUser { get; set; }
public void OnPostLogin()
{
//lists in database for every user with the input "UserNameLogin" username
foreach(DataRow dr in db.ParametryUzivatele(UserNameLogin).Rows)
{
if(PasswordLogin == dr[2].ToString())
{
//the inside of an if statement is gonna be replaced with BCrypt verification
//if password matches, it saves all the info from the database about the user in to the currentUser object.
currentUser = new(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString());
}
}
}
the current user is stored as an object of type User (model class). Right now it is stored in the back of the LoginPage, but after leaving the page, the object gets a new instance, and loses the values. Where and how should i save the code?
In my opinion, If you want to store the current user information across multiple pages, You can use Session to achieve it.
Create an extension method on session in a static class:
public static class TestSession
{
//set session
public static void SetObjectsession(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
//get session
public static T GetObjectsession<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
In OnPostLogin()
method
currentUser = new(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString());
HttpContext.Session.SetObjectsession("currentuser", currentUser );
In other pages use:
var result = HttpContext.Session.GetObjectsession<User>("currentuser");
to get the value of currentUser.
====================Update=================
I put the SetObjectsession
method into my privacy.cshtml.cs
, When I first access Index.cshtml
, HttpContext.Session.GetObjectsession<User>("currentuser")
will be null. After i access privacy and access Index.cshtml
again, It will have value.
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
var reuslt = HttpContext.Session.GetObjectsession<User>("currentuser");
}
@if (reuslt != null)
{
<h1>@reuslt.UserName</h1>
}
else
{
<h1>current user is null</h1>
}
Gif Demo