I have already searched similar questions, but since some of the Syntax has changed, I haven't found the answer I am looking for yet.
I am trying to pass a UserID from the Login/HomeController, so alle Controller/Views of the application can access it. The Login is hard coded at the moment, as I am simply trying to pass a value right now.
Session["key"]
does not work and neither does HttpContext.Current
, which doesn't even exist in the newest MVC version.
In the HomeController itself I can add values with HttpContext.Session.SetString(Key, "string")
but I do not know how to access it in the other controllers/views.
I have found IHttpContextAccessor
, but since I have to pass this as a parameter in every single constructor in all the class I want to use it and I already pass a cache parameter, it seems rather 'overkill'
Is there no better way to pass a UserID to all controller?
This is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<ILocationContainer, LocationContainer>();
services.AddDistributedMemoryCache();
services.AddHttpContextAccessor();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
This is my code in the Controller
public IActionResult Login()
{
HttpContext.Session.SetString(UserAccount, "blabla");
HttpContext.Session.SetString(UserRole, "admin");
return RedirectToAction("Index", "Home");
}