访问Asp Core 2 View中的Session对象

And*_*ham 6 c# asp.net-mvc razor asp.net-core asp.net-core-2.0

我想在视图中显示Session.那可能吗?我在我看来尝试这个

<div class="content-header col-xs-12">
   <h1>Welcome, @HttpContext.Session.GetString("userLoggedName")</h1>
</div>
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误

严重级代码描述项目文件行抑制状态错误 CS0120 非静态字段,方法或属性"HttpContext.Session"需要对象引用

任何帮助,我将不胜感激.谢谢

Shy*_*yju 8

您可以将IHttpContextAccessor实现注入视图并使用它来获取Session对象

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<h1>@HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")</h1>
Run Code Online (Sandbox Code Playgroud)

假设您已经在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?}");

    });
}
Run Code Online (Sandbox Code Playgroud)