我想在视图中显示Session。那可能吗? 我在我看来尝试了这个
<div class="content-header col-xs-12">
<h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>
但是我收到了错误
严重级代码说明项目文件行抑制状态错误 CS0120 非静态字段,方法或属性需要对象引用&lt; HttpContext.Session&#39;
任何帮助,我将不胜感激。感谢
答案 0 :(得分:7)
您可以将IHttpContextAccessor
实现注入视图并使用它来获取Session对象
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>
假设您已经在Startup类中启用了启用会话的所有设置。
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?}");
});
}