Reputation: 87
I am new to .Net and I am building a web application where I want to create a session when a user logs in or registers and confirms registration. For logging in I have a razor page: Login where it simply prompts the user for their Username and Password which should be in my sql server and validated. Once it checks that the valid user flag is correct I want to create the session and send the user to Index for now. Then in Index I want to see if the session has been created and I want to read the value within the session and display it onto the Index view to confirm that the user info has been captured.
My Login.cs file looks like this:
public ActionResult OnPost(string UserName, string Password)
{
if (!ModelState.IsValid)
{
return Page();
}
if(accountService.ValidateUserLogin(UserName, Password) == 1)
{
string Email = accountService.UsernameGetEmail(UserName);
HttpContext.Session.SetString(Email, TempData["email"].ToString());
return RedirectToPage("/Index");
}
else
{
//report error to user
return Page();
}
}
This is where I try to capture the session info in my Index.cs page:
public void OnGet()
{
if (HttpContext.Session.Id != null)
{
SessionEmail = HttpContext.Session.GetString("Email");
ViewData["SessionEmail"] = SessionEmail;
}
}
This is the piece of html where I try to display that SessionEmail onto the view but it is null upon initialization of SessionEmail inside the index.cs file.
<div>
@{
if( ViewData["SessionEmail"] != null)
{
<p> Hello! @ViewData["SessionEmail"].ToString() </p>
}
}
</div>
Hopefully you can point out my mistakes here and how I try to set up a session. After I am able to set up a session I am going to edit my layout's navbar so that it will change if a user is signed in or not so maybe if you can point out how I can go about this with sessions that would be great, perhaps: httpcontext.session.IsAvailable? Also, I do have addSession and useSession in my startup as well.
Upvotes: 0
Views: 1566
Reputation: 4634
Try this:
HttpContext.Session.SetString("Email", Email);
The reason is that you're getting the user's email address here:
string Email = accountService.UsernameGetEmail(UserName);
Then you're trying to save it to the session using the SetString
extension method. That method takes a key
as the first argument and the value
as the second.
Later, you are calling the GetString
extension method with a key
of "Email":
SessionEmail = HttpContext.Session.GetString("Email");
So you need to set the value
with that same key
:
Upvotes: 2