【发布时间】:2020-06-19 16:48:08
【问题描述】:
我已经搜索过类似的问题,但由于一些语法发生了变化,我还没有找到我正在寻找的答案。
我正在尝试从 Login/HomeController 传递用户 ID,因此应用程序的所有控制器/视图都可以访问它。登录目前是硬编码的,因为我现在只是想传递一个值。
Session["key"] 不起作用,HttpContext.Current 也不起作用,它甚至在最新的 MVC 版本中都不存在。
在 HomeController 本身中,我可以使用 HttpContext.Session.SetString(Key, "string") 添加值
但我不知道如何在其他控制器/视图中访问它。
我找到了IHttpContextAccessor,但由于我必须在我想使用它的所有类中的每个构造函数中将它作为参数传递,而且我已经传递了一个缓存参数,这似乎有点“矫枉过正”
有没有更好的方法将 UserID 传递给所有控制器?
这是我的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?}");
});
}
这是我在控制器中的代码
public IActionResult Login()
{
HttpContext.Session.SetString(UserAccount, "blabla");
HttpContext.Session.SetString(UserRole, "admin");
return RedirectToAction("Index", "Home");
}
【问题讨论】:
-
这正是您不需要传递的那种数据。如果您使用身份,只需在需要时使用可用的机制来获取此数据。
标签: c# asp.net-core model-view-controller