Search code examples
c#sessionasp.net-corehttpcontext

Asp.Net core/Razor Pages strange session behaviour: session is thrown away every second time


I have a Razor Pages application where I have one really simple section where the User enters an ID and gets redirected to a page that displays a certain content.

When the user enters the ID I'm setting the Session variable like this:

HttpContext.Session.Clear();
HttpContext.SignOutAsync();
foreach(var cookie in Request.Cookies.Keys)
{
    Response.Cookies.Delete(cookie);
}
HttpContext.Session.SetInt32("Token", 12345);
return Redirect("/DisplayPresentation");

The reason why i'm deleting all the cookies and signing out, is because I want to make sure there's nothing else in the current session.

Basically i'm receiving that session value on the redirected page, simply like this:

int tokenId = HttpContext.Session.GetInt32("Token") ?? default(int);

For whatever reason I cannot explain myself, every second time i'm doing this "login" process the session gets thrown away by the server, therefore the tokenId will be 0.

I noticed that I have a normal Authorization system for a different section of the application, so maybe that's doing funny stuff.

Any help would be highly appreciated. Thank you in advance! (PS: I hope I have provided enough information for the problem)


Solution

  • Deleting the cookies removes the cookie that keeps track of session state. So by deleting the cookies, you are effectively removing the session state and forcing a new one to be created. So:

    1. Request 1, it sets up the integer in session.
    2. Request 2 sets up session with the integer then deletes the session cookie which establishes a new session without the cookie.
    3. Request 3 gets the new session which doesn't include the integer.