Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Session object inside an Asp Core 2 View

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

like image 923
Andhika Kurnia Aufa Azham Avatar asked Oct 22 '17 17:10

Andhika Kurnia Aufa Azham


People also ask

Can we use session in ASPX page?

You can't, JavasSript is used for client side scripting on the browser, and cannot access a Session object from a server. JavaScript runs in the clients browser, your Session object is exposed by the server. There's disconnected space between them.

Can we use session in .NET Core?

ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID. The cookie session ID: Is sent to the app with each request. Is used by the app to fetch the session data.

How can use session value in MVC view?

The Session value will be displayed using Razor Syntax in ASP.Net MVC. In the below example, a string value is set in the Session object in Controller and it is then displayed in View using Razor Syntax.

How do you use a session in razor pages?

Razor PageModel (Code-Behind) Session property. When the Get Session Button is clicked, the following Handler method is executed. Inside this Handler method, the Session variable name is received as parameter. Then the value of the Session object is fetched using GetString method of the HttpContext.


1 Answers

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

    });
}
like image 52
Shyju Avatar answered Oct 05 '22 10:10

Shyju