Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access session variable in razor view .net core 2

I'm trying to access session storage in a razor view for a .net core 2.0 project. Is there any equivalent for @Session["key"] in a .net 2.0 view? I have not found a working example of how to do this - I am getting this error using the methods I have found:

An object reference is required for the non-static field, method, or propery HttpContext.Session

View:

@using Microsoft.AspNetCore.Http

[HTML button that needs to be hidden/shown based on trigger]

@section scripts {
<script>
    var filteredResults = '@HttpContext.Session.GetString("isFiltered")';
</script>
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
        });

        services.AddMvc();

        // Added - uses IOptions<T> for your settings.
        // Added - replacement for the configuration manager
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //exception handler stuff
        //rewrite http to https
        //authentication
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
like image 961
Ella Avatar asked Oct 24 '17 22:10

Ella


People also ask

How can use session value in MVC view?

So this is very simple. Go to the view where you want to retrieve the value of session. Add a Hidden field there like this: <input type="hidden" value="@Session["username"]" id="myHiddenVar" />

Can we use session in .NET Core?

Session state. Session state is an ASP.NET Core scenario for storage of user data while the user browses a web app. Session state uses a store maintained by the app to persist data across requests from a client. The session data is backed by a cache and considered ephemeral data.


2 Answers

You can do dependency injection in views, in ASP.NET Core 2.0 :)

You should inject IHttpContextAccessor implementation to your view and use it to get the HttpContext and Session object from that.

@using Microsoft.AspNetCore.Http @inject IHttpContextAccessor HttpContextAccessor <script>    var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';    alert(isFiltered); </script> 

This should work assuming you have the relevant code in the Startup.cs class to enable session.

public void ConfigureServices(IServiceCollection services) {     services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));     services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) {     app.UseSession();       app.UseMvc(routes =>     {         routes.MapRoute(             name: "default",             template: "{controller=Home}/{action=Index}/{id?}");      }); } 

To set session in a controller, you do the same thing. Inject the IHttpContextAccessor to your controller and use that

public class HomeController : Controller {    private readonly ISession session;    public HomeController(IHttpContextAccessor httpContextAccessor)    {       this.session = httpContextAccessor.HttpContext.Session;    }    public IActionResult Index()    {      this.session.SetString("isFiltered","YES");      return Content("This action method set session variable value");    } } 

Use Session appropriately. If you are trying to pass some data specific to the current page, (ex : Whether the grid data is filtered or not , which is very specific to the current request), you should not be using session for that. Consider using a view model and have a property in that which you can use to pass this data. You can always pass these values to partial views as additional data through the view data dictionary as needed.

Remember, Http is stateless. When adding stateful behavior to that, make sure you are doing it for the right reason.

like image 192
Shyju Avatar answered Oct 09 '22 15:10

Shyju


put this at the top of the razor page

@using Microsoft.AspNetCore.Http;

then you can easily access session variables like that

<h1>@Context.Session.GetString("MyAwesomeSessionValue")</h1>

if you get null values , make sure you include that in your Startup.cs

& make sure that options.CheckConsentNeeded = context is set to false

For more information about CheckConsentNeeded check this GDPR

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => true;
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set session timeout value
                options.IdleTimeout = TimeSpan.FromSeconds(30);
                options.Cookie.HttpOnly = true;
            });
        }

Also make sure you are adding app.UseSession(); to your app pipeline in Configure function

for more info about Sessions in Asp.net Core check this link Sessions in Asp.net Core

tested on .net core 2.1

like image 34
Mawardy Avatar answered Oct 09 '22 14:10

Mawardy