Accessing Session object inside an Asp Core 2 View

前端 未结 1 718
失恋的感觉
失恋的感觉 2021-02-20 05:31

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

Welcome, @HttpContext.S

1条回答
  •  醉酒成梦
    2021-02-20 05:47

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

    @using Microsoft.AspNetCore.Http
    @inject IHttpContextAccessor HttpContextAccessor
    

    @HttpContextAccessor.HttpContext.Session.GetString("userLoggedName")

    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?}");
    
        });
    }
    

    0 讨论(0)
提交回复
热议问题