asp.net-mvcrazorasp.net-coreasp.net-core-2.0

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

Solution

  • 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.