Accessing Session object inside an Asp Core 2 View

北战南征 提交于 2020-01-02 03:45:07

问题


I want to show Session in view. Is that possible? I try with this in my view

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

But i get an error

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'

Any help, i will appreciate it. Thanks


回答1:


You can inject IHttpContextAccessor implementation to your view and use it to get the Session object

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

Assuming you already have everything setup for enabling session in the Startup 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?}");

    });
}


来源:https://stackoverflow.com/questions/46877349/accessing-session-object-inside-an-asp-core-2-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!