在 Asp 核心 2 视图中访问会话对象
Accessing Session object inside an Asp Core 2 View
我想在视图中显示会话。那可能吗?
在我看来,我尝试这样做
<div class="content-header col-xs-12">
<h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>
但是我得到一个错误
Severity Code Description Project File Line Suppression State Error
CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'
任何帮助,我将不胜感激。谢谢
您可以将 IHttpContextAccessor
实现注入您的视图并使用它来获取 Session 对象
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>
假设您已经在启动 class 中设置了启用会话的所有设置。
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession(); // This line is needed
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我想在视图中显示会话。那可能吗? 在我看来,我尝试这样做
<div class="content-header col-xs-12">
<h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>
但是我得到一个错误
Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session'
任何帮助,我将不胜感激。谢谢
您可以将 IHttpContextAccessor
实现注入您的视图并使用它来获取 Session 对象
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>
假设您已经在启动 class 中设置了启用会话的所有设置。
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession(); // This line is needed
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}