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);
}
Top comments (0)