Technology Apr 17, 2026 · 2 min read

Using sessions in asp.net anyone have any insight?

here is how i set it up in program.cs : builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); // [cite: 16] options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); var app = builder.Buil...

DE
DEV Community
by FaithInErrorsZORO
Using sessions in asp.net anyone have any insight?

here is how i set it up in program.cs :

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10); // [cite: 16]
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});

var app = builder.Build();

[cite_start]// 2. Add Session Middleware (between Routing and Endpoints) [cite: 17]
app.UseRouting();
app.UseSession();
app.UseAuthorization();

here is how i reference the session

[[HttpPost]
public IActionResult Index(string lastName)
{
var player = _context.Players.FirstOrDefault(p => p.LastName == lastName);

if (player == null)
{
    ViewBag.Message = "No player found with that last name.";
    return View();
}

// Store IDs in Session for later use
HttpContext.Session.SetString("playerId", player.PlayerId.ToString());
HttpContext.Session.SetInt32("coachId", player.CoachId ?? 0);
HttpContext.Session.SetInt32("teamId", player.TeamId ?? 0);

return View("Display", player);

}

action to show the stats:

public IActionResult ShowStats()
{
var pId = HttpContext.Session.GetString("playerId");

var playerWithStats = _context.Players
    .Include(p => p.GameRecords)
        .ThenInclude(gr => gr.StatCategory)
    .FirstOrDefault(p => p.PlayerId.ToString() == pId);

return View(playerWithStats);

}

dif types :

public IActionResult ShowCoach()
{
var pId = HttpContext.Session.GetString("playerId");
var cId = HttpContext.Session.GetInt32("coachId");
var tId = HttpContext.Session.GetInt32("teamId");

var player = _context.Players.Find(int.Parse(pId));
var coach = _context.Coaches.Find(cId);
var team = _context.Teams.Find(tId);

// Join class/ViewModel to pass all three objects to the view
var viewModel = new PlayerCoachTeamViewModel { 
    Player = player, 
    Coach = coach, 
    Team = team 
};

return View(viewModel);

}

DE
Source

This article was originally published by DEV Community and written by FaithInErrorsZORO.

Read original article on DEV Community
Back to Discover

Reading List