Session - Set/Get session in Web


Scenario:

Create a Sign on service to allow creation of users in our app. Add user details to session

Solution:

  1. Add NuGet Microsoft.AspNet.Core.Session
  2. In Startup.cs under Configure method

  3. //add before UseEndpoints or if using Mvc as before UseMvc
    app.UseSession();

  4. In Startup.cs under ConfigureServices method

  5. 1
    2
    services.AddDistributedMemoryCache();
    services.AddSession(options => { options.Cookie.Name = ".solutionName.Session"; options.IdleTimeout = TimeSpan.FromMinutes(5); });
    

  6. Set session as below

  7.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    try
    {
     var userList = string.Join(",", result.Item2.ToArray());
     HttpContext.Session.SetString("users", userList + " in Home controller");
     ViewBag.success = true;
     ViewBag.Name = userList;
    }
    catch (Exception e)
    {
     throw;
    }

  8. Read session data as below

  9.  
    1
    2
     var users = HttpContext.Session.GetString("users");
     ViewBag.Name = users;
    
    

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...