Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Sessions in ASP vNext

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 ?

like image 920
F Andrei Avatar asked Mar 29 '15 15:03

F Andrei


People also ask

How can use session in controller in ASP.NET Core?

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.


2 Answers

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);
        }
    }
}
like image 183
Bart Calixto Avatar answered Nov 01 '22 04:11

Bart Calixto


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

like image 26
agua from mars Avatar answered Nov 01 '22 05:11

agua from mars