Search code examples
c#asp.net-coresession-variablesasp.net-core-2.1razor-pages

Asp.Net Core Razor pages, session variable is not accessible from other views/razor models


I am saving session variable in login page,

Guid sessionId = Guid.NewGuid();

HttpContext.Session.SetString("sessionId",sessionId.ToString());
Response.Cookies.Append("sessionId", sessionId.ToString());

Now I access this variable like this:

string sessionId = Request.Cookies["sessionId"];            

if (!String.IsNullOrEmpty(sessionId) && sessionId.Equals(HttpContext.Session.GetString("sessionId")))
{
    return RedirectToPage("/LoggedIn/Index");
}

return Page();

This code I use on the same razor page (login page) in which session Id is declared, however if I use the above code in any other razor view page, I cannot access this session variable. It is only accessible on the same page it was saved.

What can I possibly be doing wrong ?


Solution

  • I had to change the entire context of my previous comment. Here is the "Correct Answer".

    Just make sure you have checked below steps:

    1. services.AddDistributedMemoryCache() memory is configured for caching.
    2. services.AddSession() you've configured session.
    3. Here's where people make the mistake app.UseSession() must be called after app.UseCookiePolicy() and before app.UseMvc() .

    **Note that a RedirectToPage()call does not affect/change session variables at all. **

    These steps look basic but actually step 3 is the answer you're looking for. Your code looks absolutely fine.

    Here's the Middleware Ordering as outlined by Rick Anderson and Steve Smith https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/index?view=aspnetcore-2.2#order

    Sometimes the problem might be caused by CheckConsentNeeded = context => true being set to true when you configure your CookiePolicyOptions. Just set it to false if you have <CookiePolicyOptions> configured. If you want to leave it as true you must then configure cookie and set Cookie.IsEssential = true; Then the session will survive any redirect action.