How can I use session variables in ASP MVC 6 ?
I couldn't find a working sample on how to store and use session variables . Can anyone help ?
To use session in our Application, we need to add this package as a dependency in project. json file. The next step is to configure session in Startup class. We need to call "AddSession" method in ConfigureServices method of startup class.
add package "Microsoft.AspNet.Session": "1.0.0-beta8"
to project.json and then using Microsoft.AspNet.Http;
inside that namespace you have extension methods for context.
you also need to use it with DI on Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession();
}
Here's a sample controller :
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
namespace MvcWebApp.Controllers
{
[Route("[controller]")]
public class SomeController : Controller
{
public async Task<IActionResult> Edit()
{
HttpContext.Session.SetInt("myVar", 35);
}
}
}
there is a sample on the session repo on github: https://github.com/aspnet/Session/tree/release
And you can access to the session by the Controler's Session
property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With