public class UserService
{
public int UserId { get; set; }
}
builder.Services.AddSingleton
public IActionResult Login(string username, string password)
{
// Authenticate the user and get their ID
int userId = …
// Set the UserId in the UserService class
var userService = HttpContext.RequestServices.GetService
userService.UserId = userId;
return RedirectToAction(“Index”, “Home”);
}
In Controller
public IActionResult Index()
{
var userService = HttpContext.RequestServices.GetService
var userId = userService?.UserId ?? 0;
ViewData[“userId”] = userId;
return View();
}
public async Task
{
await HttpContext.SignOutAsync();
var userService = HttpContext.RequestServices.GetService
if (userService != null)
{
userService.UserId = 0;
}
return RedirectToAction(“Index”, “Hukam”);
}
In View
@using EkHukam_Gurudwara.Data
@{
ViewData[“Title”] = “Dashboard”;
var userService = (UserService)ViewContext.HttpContext.RequestServices.GetService(typeof(UserService));
var @UID = (userService?.UserId ?? 0);
}