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